开发者

Guice inject in servlet

开发者 https://www.devze.com 2023-03-08 09:53 出处:网络
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'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 sco开发者_如何学运维pe 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消