模糊的机器人腿有效吗?

发布于 2024-10-24 01:56:12 字数 567 浏览 2 评论 0原文

Guice 常见问题解答中,他们讨论了通过注释区分多个实例(例如的)。

我的问题:我可以在没有注释的情况下将 Impl 绑定到接口,然后使用注释将另一个 Impl 绑定到同一个接口吗?基本上我的第一个 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(..) 是否被认为是不好的形式?只是试图避免创建大量注释类,但又希望能够重构的好处。

In the Guice FAQ, they talk about differentiating multiple instances with annotations (kind of).

My question: Can I bind a Impl to an Interface without an annotation, and bind another Impl to that same Interface with an annotation? Basically my first impl is going to act as a container for the others.

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

Bonus question, is our usage of Names.named(..) considered bad form? Just trying to avoid creating a ton of annotation classes, yet wanted the benefits of being able to refactor.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放肆 2024-10-31 01:56:12

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

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

Yup, that should just work. You might want to also look at Multibindings, which is designed for scenarios like this one. The composite implementation would inject the set of interfaces:

public class CompositeSecurityAuthorizer {
    @Inject 
    CompositeSecurityAuthorizer(Set<SecurityAuthorizer> authorizers) {
        ...
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文