【问题标题】:Are ambiguous robot legs valid?模棱两可的机器人腿有效吗?
【发布时间】:2011-03-18 15:13:16
【问题描述】:

Guice FAQ 中,他们谈到了用注释区分多个实例(有点)。

我的问题:我可以将一个 Impl 绑定到一个没有注释的接口,并将另一个 Impl 绑定到同一个接口 with 一个注释吗?基本上我的第一个 impl 将充当其他 impl 的容器。

bind(SecurityAuthorizer.class).to(CompositeSecurityAuthorizer.class);
bind(SecurityAuthorizer.class)
    .annotatedWith(Names.named(ComponentAuthorizer.class.getSimpleName()))
    .to(ComponentAuthorizer.class).in(Singleton.class);

额外问题,我们对 Names.named(..) 的使用是否被认为是错误的形式?只是想避免创建大量注释类,但又想要能够重构的好处。

【问题讨论】:

    标签: dependency-injection annotations guice robot-legs-problem


    【解决方案1】:

    是的,应该可以。您可能还想查看Multibindings,它专为此类场景而设计。复合实现将注入一组接口:

    public class CompositeSecurityAuthorizer {
        @Inject 
        CompositeSecurityAuthorizer(Set<SecurityAuthorizer> authorizers) {
            ...
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2014-08-12
    相关资源
    最近更新 更多