有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

名为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) 个答案

  1. # 1 楼答案

    这可能只是在“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();
        }