brakebg brakebg - 1 year ago 148
Java Question

Guice inject in servlet

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 ..

public class Bean {
private String user;
private String pass;

// constructor which is @inject

// getters and setters

Here i've got a servlet

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
} Guice configuration errors:

1) No scope is bound to
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download