Guice inject in servlet

10,517

You're creating and using an Injector inside the doGet method on your servlet... it has no chance to be aware of scope or of the current request or anything!

Guice Servlet requires that you set up all requests to go through the GuiceFilter and that you create a subclass of GuiceServletContextListener that creates the Injector that your whole application will use. This is all described in Guice user guide in the Servlets section.

Once you've done that, you can @Inject things in to your MainServlet (even using an @Inject annotated constructor). To get a request scoped instance of Bean inside the servlet, you'd need to inject a Provider<Bean> (since Bean has a smaller scope than the singleton servlet). Within a request, you can call beanProvider.get() to get the Bean for the current request.

Note that servlets are singletons because that's how they work in the normal Java servlet world as well... they're each only created once per application and that single instance is used for all requests to that servlet.

Share:
10,517
brakebg
Author by

brakebg

Updated on June 08, 2022

Comments

  • brakebg
    brakebg almost 2 years

    I'm fresh new in Google Guice framework and i have a question regarding injecting in guice servlet and using RequestScope. Ok let me give some example from my code just to make the things clearly.

    I have a bean class for example Bean ..

    @RequestScope
    public class Bean {
        private String user;
        private String pass;
    
        // constructor which is @inject 
    
        // getters and setters
    }
    

    Here i've got a servlet

    @Singleton
    public class MainServlet extends HttpServlet {
        doGet(HttpServletRequest request, HttpServletResponse response) {
            .... some code 
            Injector injector = Guice.createInjector();
            ValidUser validUser = injector.getInstance(ValidUser.class)
            // Here i got the below exception
        }
    }
    
    
    
    com.google.inject.ConfigurationException: Guice configuration errors:
    
    1) No scope is bound to com.google.inject.servlet.RequestScoped.
      at Bean.class while locating Bean
    

    It's interesting here that servlet scope is singleton as we know. And also how can i get from the http request - Bean instance?? because as far as i understand after a instance of a Bean class is injected it goes in the http request, right?

    Any help or example is welcome. Thanks Br

  • Stefano Bossi
    Stefano Bossi over 3 years
    Wow, this is a good explanation but a little bit hard for a new Guice user like me, anyway thanks for the hint.