【问题标题】:Getting an instance within a Guice Module在 Guice 模块中获取实例
【发布时间】:2011-03-17 02:09:26
【问题描述】:

我有这门课:

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

我想为authorizers 字段注入一个List&lt;SecurityAuthorizer&gt; 值。

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

@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;
}

我的问题嵌入在代码 cmets 中。当我将StoreAuthorizer 添加到List&lt;SecurityAuthorizer&gt; 时:

  • 我如何确保它与其他StoreAuthorizer 引用的实例相同?
  • Guice 只是在幕后做的事情,所以 new StoreAuthorizer() 真的在幕后调用 getInstance() 的 impl 吗?

【问题讨论】:

    标签: dependency-injection singleton guice


    【解决方案1】:

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

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

    顺便说一句,您可能需要考虑使用 Guice Multibindings 扩展来创建 Set&lt;SecurityAuthorizer&gt;,而不是自己创建。

    【讨论】:

    • 我忘记了 MultiBinder。所以像这样的东西? Multibinder securityBinder = Multibinder.newSetBinder(binder(), SecurityAuthorizer.class); securityBinder.addBinding().to(StoreAuthorizer.class);
    • @Snekse:是的,类似的。
    • Opps,看起来 Multibinder 与 Gin 不兼容。 code.google.com/p/google-gin/issues/detail?id=111
    • 如果我需要向 authList 添加 15 个 SecurityAuthorizer 对象,您的回答会不会有所不同?
    • @Snekse:嗯,你需要 15 个 SecurityAuthorizer 参数给方法,通过绑定注释或类型或其他来区分。这会很难看,但我认为它应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多