根据类的Annotation绑定构造函数参数 [英] Binding a constructor argument based on the Annotation of the class

查看:144
本文介绍了根据类的Annotation绑定构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口: InterfaceA .

我有一堂课: ConcreteA .

我也有两个注释: @AnnotA @AnnotB .

我完成了以下绑定:

bind(InterfaceA).annotatedWith(AnnotA).to(ConcreteA);
bind(InterfaceA).annotatedWith(AnnotB).to(ConcreteA);

接下来,类ConcreteA有一个构造函数,该构造函数接受名为 hostName String参数.

Next, class ConcreteA has a constructor that takes a String argument called hostName.

class ConcreteA
{
    @Inject
    public ConcreteA(@Named("hostName") hostName) {
    }

    ... <rest of class>
}

我需要代码来描述以下内容:

如果ConcretaA使用@AnnotA,则将主机名与字符串值本地主机"绑定

如果ConcreteA使用@AnnotB,则将hostName绑定为字符串值"externalhost"

有解决方案的想法吗?

推荐答案

我认为在您的情况下,您可以考虑将每个绑定放在其自己的私有模块中.

I think in your case, you might consider putting each binding in its own private module.

class MyModule() { 
  install(new PrivateModule() {
    public void configure() {
       bind(InterfaceA).to(ConcreteA);
       bind(String.class).annotatedWith(Names.named("hostName").to("localhost");
       expose(InterfaceA).annotatedWith(AnnotA.class);
    }});
  install(new PrivateModule() {
    public void configure() {
       bind(InterfaceA).to(ConcreteB);
       bind(String.class).annotatedWith(Names.named("hostName").to("externalhost");
       expose(InterfaceA).annotatedWith(AnnotB.class);
    }});
}

(这是从内存中提取的,语法可能不是100%正确.)

(This is from memory and syntax may not be 100% correct.)

有关更多详细信息,请从 Guice常见问题解答开始,然后搜索关于机器人腿"的页面-我不是在开玩笑:)

For more detail, start with the Guice FAQ, and search that page for "robot legs" -- I'm not joking :)

常见问题解答中该部分的两个附加链接后面有更多详细信息.

There is even more detail behind the two additional links from that section of the FAQ.

这篇关于根据类的Annotation绑定构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆