gpt4 book ai didi

java - Guice 不加载绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 09:18:51 24 4
gpt4 key购买 nike

接口(interface) -

public interface Add {
public int add(int a, int b)
}

实现 1 -

class MartianAdd implements Add 
public int add(int a, int b) {
return -a+b;
}
}

实现2-

public class SimpleAdd implements Add {
public SimpleAdd() {}
public int add(int a, int b) {
return a + b
}
}


class Bindings extends AbstractModule {
protected void configure() {
bind(Add).annotatedWith(Names.named('Earth')).to(SimpleAdd)
bind(Add).annotatedWith(Names.named('Mars')).to(MartianAdd)
}
}

主类-

class Test {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Bindings())
@Named('Mars') Add a = injector.getInstance(Add)
print a.class
print a.add(5, 8)
}
}

异常 -

Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for in.ksharma.Add was bound.
while locating in.ksharma.Add

为什么 Guice 不加载我的绑定(bind)?

最佳答案

这就是问题所在,我相信:

@Named('Mars') Add a = injector.getInstance(Add)

您只是请求 Add 的实例 - 事实上,您要将结果分配给的变量具有 @Named 注释与 Guice 无关。我相信您需要将 Injector.getInstance(Key) 与正确类的键一起使用具有正确的名称绑定(bind),例如

Add add = injector.getInstance(Key.get(Add, Names.named('Mars')))

关于java - Guice 不加载绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18269853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com