Get an Guice Injector in a web application
I'm looking how I could get an Injector using Guice in a web application. I already found a solution using ServletContext, but I'm not really satisfied by this solution, because it breaks the layer architecture of the ap开发者_StackOverflow中文版plication. I'm not okay with using a ServletContext in the deeper layers of the app. Do you know another way?
An obvious solution would be to create my own singleton to host the Injector, but it seems to be that Guice should offer some out-of-the-box way to do this. I just can't find one yet...
Assuming you're using Guice Servlet and assuming the class you want the Injector in is injected itself, just inject the Injector.
Your application lifecycle is fully controlled by the servlet container, so the usage of a context listener to start the initialization process of your application is the logical result of that fact. Thus I wouldn’t say that that fact in itself is not breaking the layered architecture, just like a web request starting activity in the model layer neither breaks the layered architecture.
But in order to not break the layered architecture, the servlet context listener shouldn’t involve itself with the details of the other layers, it should only initiate the initialization. Thus all Guice related code, for example a Guice injector factory, should be located in its own layer. The role of the context listener should be limited to a call that starts the initialization (for example: MyGuiceFactory.init() or MyApp.init()).
精彩评论