Java 类应该具有 int MY_LISTENER_PORT
,并从属性文件中注入(inject) my.listener.port 值:
@Singleton
public class MyListener {
@Inject
@Named("my.listener.port")
private int MY_LISTENER_PORT;
public MyListener(){
start();
}
public void start() {
System.out.println("Port: " + MY_LISTENER_PORT);
}
}
它在 Guice 中被绑定(bind)为热切的单例:
public class BootstrapServletModule extends ServletModule {
@Override
protected void configureServlets() {
...
bind(MyListener.class).asEagerSingleton();
...
}
}
有时,当 Tomcat 启动时,我会正确地向 MY_LISTENER_PORT 注入(inject)值,例如:“端口:9999”。有时,它没有注入(inject),我得到“端口:0”。为什么会这样?
最佳答案
这可能只是你的构造函数在“MY_LISTER_PORT”有机会被注入(inject)之前触发
https://github.com/google/guice/wiki/InjectionPoints
https://github.com/google/guice/wiki/Bootstrap
构造函数在方法和字段之前注入(inject),因为您必须在注入(inject)其成员之前构造一个实例。
Injections are performed in a specific order. All fields are injected and then all methods. Within the fields, supertype fields are injected before subtype fields. Similarly, supertype methods are injected before subtype methods.
用户构造函数注入(inject)
@Inject
public MyListener(@Named("my.listener.port") int port){
this.MY_LISTER_PORT = port;
start();
}
关于java - Guice 在急切的单例中命名注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39999621/