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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With