【发布时间】:2015-03-20 13:15:09
【问题描述】:
我有一个界面
public interface ConfFileLoader {
public Map<String, Object> getResultMap() throws SecurityException, IOException;
}
以及将其实现为的类
public class ConfYamlLoader implements ConfFileLoader{
@Override
public Map<String, Object> getResultMap() throws SecurityException, IOException {
}
}
并且有一个注入器类
public class AppInjector extends AbstractModule {
@Override
public void configure() {
bind(ConfFileLoader.class).to(ConfYamlLoader.class);
}
}
现在的问题是我有一个类
public class TI {
@Inject
private ConfFileLoader confFileLoader;
public void test(){
System.out.println("yeah tesrintY>>>>>>>>>>>>>>>>>>>"+confFileLoader);
}
}
它给出了异常
Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors:
1) No implementation for com.exzeo.conf.ConfFileLoader was bound.
while locating com.exzeo.conf.ConfFileLoader
for field at com.exzeo.automate.HCPCI.TI.confFileLoader(TI.java:10)
while locating com.exzeo.automate.HCPCI.TI
但是当我使用@ConfYamlLoader 时,它可以正常工作
public class TI {
@Inject
private ConfYamlLoader confFileLoader;
public void test(){
System.out.println("yeah tesrintY>>>>>>>>>>>>>>>>>>>"+confFileLoader);
}
}
上面的这个类工作正常
所以在调查中我发现当我在 ConfFileLoader 上添加 @implemetedby 时它可以正常工作
@ImplementedBy(ConfYamlLoader.class)
public interface ConfFileLoader {
public Map<String, Object> getResultMap() throws SecurityException, IOException;
}
如果我已经在绑定模块中绑定它,我无法理解为什么我需要做@ImplementedBy。据我了解,@implementedby 等同于 bind()。
如果我缺少任何东西并且我使用的是 guice 版本 3,请告诉我
【问题讨论】:
-
发生这种情况的唯一原因是您根本没有使用您的模块。再次检查您确实将
AppInjector实例传递给Guice.createInjector()。 -
注射器注射器 = Guice.createInjector(new AppInjector());我正在这样做@VladimirMatveev
-
抱歉,我无法重现您的问题。请参阅this 要点。它包含您提供的代码和 Main 中的一小段粘合代码。它非常适合我,在调用
test()方法时打印guicex.ConfYamlLoader@5dbc26ee。 -
@VladimirMatveev 抱歉,我没有提到重要的事情。我正在使用 testng 来运行一个测试类,并在该类中注入 ConFileLoader。我使用 testng 作为 TestNG tng = new TestNG(); tng.setXmlSuites(xmlSuiteBuilder.getSuites()); tng.run(); xml 套件构建器提供测试类的详细信息