名为inject的java Guice在渴望的singleton中
有一个Java类应该有int 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的急切单例:
public class BootstrapServletModule extends ServletModule {
@Override
protected void configureServlets() {
...
bind(MyListener.class).asEagerSingleton();
...
}
}
有时,当Tomcat启动时,我会正确地将值注入我的_侦听器_端口,例如:“PORT:9999”。有时,它没有被注入,我得到“端口:0”。为什么会这样
# 1 楼答案
这可能只是在“MY_LISTER_PORT”有机会被注入之前,构造函数触发
https://github.com/google/guice/wiki/InjectionPoints
https://github.com/google/guice/wiki/Bootstrap
构造函数在方法和字段之前被注入,因为您必须在注入实例的成员之前构造实例
用户构造函数注入