简体   繁体   English

Guice配置错误

[英]Guice configuration error

I'm trying to use Google Guice with the @Inject and @Singleton properties as follows: 我正在尝试将Google Guice与@Inject和@Singleton属性一起使用,如下所示:

I have: 我有:

  1. A Module with an empty configure() method. 具有空configure()方法的模块。
  2. An interface IFoo 一个接口IFoo
  3. A class Foo (implementing IFoo), annotated with @Singleton, with a parameter-less constructor annotated with @Inject. 一个类Foo(实现IFoo),用@Singleton注释,带有@Inject注释的无参数构造函数。 This is the single annotated constructor. 这是单个带注释的构造函数。

The classes, constructor and interface are public, and still I'm getting the following error: 类,构造函数和接口是公共的,但我仍然收到以下错误:

No implementation for IFoo was bound. 没有针对IFoo的实现。

You mean you get the error when doing this? 你的意思是你在这样做时得到错误?

IFoo foo = injector.getInstance(IFoo.class);

Well then it is obvious. 那么很明显。 If the configure() is empty how should guice know with what class to satisfy the dependency for IFoo . 如果configure()为空,那么guice应该知道哪个类满足IFoo的依赖性。

Just add this in the configure() method and it should work. 只需在configure()方法中添加它,它应该工作。 Now guice knows with what class to satisfy the dependency. 现在guice知道用什么类来满足依赖。

bind(IFoo.class).to(Foo.class);

If you don't want to configure this in the module you can annotate the interface. 如果您不想在模块中配置它,则可以注释该接口。 eg 例如

@ImplementedBy(Foo.class)
public interface IFoo {
  ...
}

The @Singleton annotations only tells guice to return the same instance for the class (the Singleton Pattern) everytime a request for the class is made via Injector.getInstance() instead of creating a new instance everytime. @Singleton注释只告诉guice每次通过Injector.getInstance()发出类的请求而不是每次都创建一个新实例时,返回该类的相同实例(Singleton模式)。 But note that this is only a Singleton per Injector rather then per Classloader. 但请注意,这只是每个Injector的Singleton而不是每个Classloader。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM