依赖注入 – 在Guice模块中获取实例

我有这门课:

public class CompositeSecurityAuthorizer implements SecurityAuthorizer {
    @inject @CompositeSecurityAuthorizerAnnot
    List<SecurityAuthorizer> authorizers; //Field Injection
}

我想向授权者字段注入List< SecurityAuthorizer>值.

在我的模块中,我有以下内容

@Override
protected void configure() {
  bind(CompositeSecurityAuthorizer.class).in(Singleton.class);
  bind(StoreAuthorizer.class).in(Singleton.class);
  bind(SecurityAuthorizer.class)
      .annotatedWith(CompositeSecurityAuthorizerAnnot.class)
      .to(CompositeSecurityAuthorizer.class);
}

@Provides @CompositeSecurityAuthorizerAnnot
List<SecurityAuthorizer> provideAuthorizersList()
{
    List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>();
    //How do I add StoreAuthorizer while maintaining a Singleton?
    //Will the line below do it through Guice magic?
    //authList.add(new StoreAuthorizer());
    return authList;
}

我的问题嵌入在代码注释中.当我将StoreAuthorizer添加到该列表< SecurityAuthorizer>时:

>我如何确保它与其他StoreAuthorizer引用的实例相同?
>这是Guice刚刚做的事情,所以新的StoreAuthorizer()真的在幕后调用了getInstance()吗?

解决方法

提供者方法允许注入参数.传递给此方法的StoreAuthorizer将是模块中的单例绑定.如果你自己打电话给构造函数,Guice不会也不能做任何神奇的事情.

@Provides @CompositeSecurityAuthorizerAnnot
List<SecurityAuthorizer> provideAuthorizersList(StoreAuthorizer storeAuthorizer)
{
    List<SecurityAuthorizer> authList = new ArrayList<SecurityAuthorizer>();
    authList.add(storeAuthorizer);
    return authList;
}

另外,您可能需要考虑使用Guice Multibindings扩展来创建Set< SecurityAuthorizer>而不是自己这样做.

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...