在Guice模块中获取一个实例

5

我有这个类:

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

我希望将authorizers字段注入一个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添加到List<SecurityAuthorizer>时:

  • 我如何确保它是与其他StoreAuthorizer引用相同的实例?
  • 这是Guice在幕后自动完成的吗,因此new StoreAuthorizer()实际上是在幕后调用getInstance()的实现?
1个回答

8

提供者方法允许注入参数。这里传递给方法的StoreAuthorizer将是您模块中绑定的单例。如果您自己调用构造函数,Guice不会也不能做任何神奇的事情。

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

顺便提一下,您可能希望考虑使用Guice Multibindings扩展来创建Set<SecurityAuthorizer>,而不是自己完成。


我忘记了 MultiBinder。所以应该像这样?Multibinder securityBinder = Multibinder.newSetBinder(binder(), SecurityAuthorizer.class); securityBinder.addBinding().to(StoreAuthorizer.class); - Snekse
@Snekse:是的,就像那样。 - ColinD
糟糕,看起来Multibinder与Gin不兼容。http://code.google.com/p/google-gin/issues/detail?id=111 - Snekse
如果我需要将15个SecurityAuthorizer对象添加到该authList中,您的回答会有所不同吗? - Snekse
@Snekse:好吧,你需要15个SecurityAuthorizer参数传递给该方法,并且可以通过绑定注释、类型或其他方式进行区分。这样做很丑陋,但我认为应该可以运行。 - ColinD
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接