【问题标题】:Google guice not working without using implemented byGoogle guice 不使用由实现的就无法工作
【发布时间】: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 套件构建器提供测试类的详细信息

标签: java guice guice-3


【解决方案1】:

你的线路

bind(ConfFileLoader.class).to(ConfYamlLoader.class);

意思是“当你要注入一个ConfFileLoader类型的值时,而是注入一个ConfYamlLoader类型的值并使用它”。

但是你仍然需要以某种方式绑定ConfYamlLoader,以便它可以被注入。

如果它有一个 @Inject-annotated 构造函数,或者一个公共的无参数构造函数(除非你在某个地方调用了 binder.requireAtInjectOnConstructors()),那么 Guice 将使用它。

否则,您将需要以某种方式绑定Provider&lt;ConfYamlLoader&gt;,方法是使用@Provides ConfYamlLoader 方法或bind(ConfYamlLoader).toProvider(...).toInstance(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-23
    • 1970-01-01
    • 2014-02-23
    • 2011-02-20
    • 1970-01-01
    • 2012-02-10
    相关资源
    最近更新 更多