problem on using injections within GuiceServletContextListener.contextInitialized

415 views
Skip to first unread message

ich du

unread,
Jan 23, 2012, 6:35:58 AM1/23/12
to google...@googlegroups.com
i try to sort up the deployment of my webapp. so i need to override contextInitilaized in GuiceServletContextListener. there i need to check the state of some module-bound objects. 
but i get problems:
i field-injected the needed objects (a logger and a external datasource) and tried to use them in contextInitialized but i get NullPointerExceptions all injected stuff is null in scope of contextInitialized (later, after deployment all injections work properly). the problem is that all guice injection starts within contextInitialized: "super.contextInitialized(servletContextEvent);"

so how to let guice inject the fields (or do i need another kind of injection?) after "super.contextInitialized(servletContextEvent);"?

thx in advance

Tim Peierls

unread,
Jan 23, 2012, 9:35:53 AM1/23/12
to google...@googlegroups.com
Does your code look like this?

    public class Main extends GuiceServletContextListener {

@Override protected Injector getInjector() {
   return Guice.createInjector(stage, 
new MyServletModule(),           
// ... other modules ...
new AbstractModule() {
   @Override protected void configure() {
requestInjection(Main.this);
   }
}
   ));
}

@Override public void contextInitialized(ServletContextEvent event) {
   super.contextInitialized(event);
   // use someField here
}

@Inject volatile SomeType someField;
    }

This pattern works for me. If it doesn't work for you, I'd like to know why not.

--tim

ich du

unread,
Jan 24, 2012, 2:45:07 AM1/24/12
to google...@googlegroups.com
in meantime i got it to work but it looks different:
public class AppGuiceContextListener extends GuiceServletContextListener {
    
    private Injector injector;
       private MetaDataService mds;
       private ServerLogger logger;

    @Override
    public final Injector getInjector() {
        injector = Guice.createInjector(new ServerModule(), new AdbServletModule());
        return injector;
    }

 
    @Override
    public final void contextInitialized(final ServletContextEvent servletContextEvent) {
        
        super.contextInitialized(servletContextEvent);
        mds = injector.getProvider(MetaDataService.class).get();
        logger = injector.getProvider(ServerLogger.class).get();
       ...
    }

  ...

}

ich du

unread,
Jan 24, 2012, 2:49:39 AM1/24/12
to google...@googlegroups.com
(i forgot that i can't edit posts :-|)

i don't know if the above better but i remembered that examples with classic main method also use the injector directly to get objects. If i would have more objects needed at start-up your way seem more elegant Tim?! So i will keep it in mind - thx.
Reply all
Reply to author
Forward
0 new messages