Servic Geek Injection

I am new to Google Guice and I have a question regarding injecting into a guice servlet and using RequestScope. Ok, let me give an example from my code to make things clear.

I have a bean class like bean ..

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

Here i have 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 

Interestingly, the servlet area is single, as we know. And also, how can I get a bean instance from an http request? because, as I understand it, after entering an instance of the bean class, it goes into an HTTP request, right?

Any help or example is appreciated. thanks br

+7
source share
1 answer

You create and use Injector inside the doGet method on your servlet ... it has no idea about the scope or current request or anything else!

Guice Servlet requires that you configure all requests to pass through GuiceFilter and create a subclass of GuiceServletContextListener that creates the Injector that your application will use. All of this is described in the Guice user guide in the Servlets section.

Once you do this, you can include @Inject in your MainServlet (even using the annotated @Inject ). To get an instance bound to a Bean request inside the servlet, you need to enter the Provider<Bean> (since the Bean has a smaller scope than the singlet servlet). In the request, you can call beanProvider.get() to get the Bean for the current request.

Note that servlets are single point because they also work in the normal Java servlet world ... each of them is created only once for each application and this single instance is used for all requests to this servlet.

+16
source

All Articles