Guice 在急切的单例中命名注入

Guice named inject in eager singleton

有 Java class 应该有 int MY_LISTENER_PORT 并从属性文件中注入 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 启动时,我会正确地向 MY_LISTENER_PORT 注入值,例如:"Port: 9999"。有时,它没有注入,我得到 "Port: 0"。为什么会这样?

这可能只是你的构造函数在 'MY_LISTER_PORT' 有机会被注入之前触发

https://github.com/google/guice/wiki/InjectionPoints

https://github.com/google/guice/wiki/Bootstrap

构造函数在方法和字段之前注入,因为您必须在注入其成员之前构造一个实例。

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
public MyListener(@Named("my.listener.port") int port){
        this.MY_LISTER_PORT = port;
        start();
    }