Justinas Jakavonis
Justinas Jakavonis

Reputation: 8798

Guice named inject in eager singleton

There is Java class which should have int MY_LISTENER_PORT with injected my.listener.port value from a properties file:

@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);
    }
}

Which is bind as eager singleton with Guice in:

public class BootstrapServletModule extends ServletModule {

     @Override
     protected void configureServlets() {
          ...
          bind(MyListener.class).asEagerSingleton();
          ...
     }
}

Sometimes when Tomcat starts up, I get properly injected value to MY_LISTENER_PORT, for example: "Port: 9999". Sometimes, it is not injected and I get "Port: 0". Why does it happen?

Upvotes: 3

Views: 1027

Answers (1)

kuhajeyan
kuhajeyan

Reputation: 11017

This is could be simply you constructor fires before 'MY_LISTER_PORT' gets chance to get injected

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

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

constructors are injected before methods and fields, as you have to construct an instance before injecting its members.

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.

User constructor injection

@Inject
public MyListener(@Named("my.listener.port") int port){
        this.MY_LISTER_PORT = port;
        start();
    }

Upvotes: 4

Related Questions