GuiceServletContextListener.getInjector should have one param: servletContext
See original GitHub issueFrom gianmarco.gherardi on February 16, 2011 11:04:39
This way, configuration parameters can be passed as constructor parameter to object. For example, this is possible in normal Java application:
public static void main(String[] args) { String fooServerAddress = args[0]; Injector injector = Guice.createInjector(new FooModule(fooServerAddress)); FooClient client = injector.getInstance(FooClient.class); … }
In Servlet application this should became:
public class AppGuiceServletContextListener extends GuiceServletContextListener {
@
Override
protected Injector getInjector(ServletContext servletContext) {
String fooServerAddress = servletContext.getInitParameter(“fooServerAddress”);
return Guice.createInjector(new FooModule(fooServerAddress));
}
}
Check also comments on https://code.google.com/p/google-guice/wiki/FrequentlyAskedQuestions and thread on http://groups.google.com/group/google-guice/browse_thread/thread/dad68e87fd94261e
_Original issue: http://code.google.com/p/google-guice/issues/detail?id=603_
Issue Analytics
- State:
- Created 9 years ago
- Comments:5
Top GitHub Comments
It would indeed be a much nicer API if getInjector took a ServletContext parameter. The existing workaround of overriding contextInitialized and caching the value is clumsy and unintuitive. It also places the burden on the subclass of ensuring that the methods are invoked in the expected order and behaving sensibly if they are not.
This is especially critical given that the without this, the obvious way of getting a ServletContext is to @Inject it into a module, which leads to a deprecation warning and the possibility of bugs due to it being injected into singleton contexts.
It would have been really easy to have included this parameter when the class was first written, now of course the problem is how to include it without breaking existing users. Perhaps the cleanest option would be:
E.g.
This has the advantage that it exposes a cleaner API that makes it much easier to figure out where and how you should obtain the ServletContext whilst not breaking any existing users.
Additional: Ironically, a couple of hours after writing this comment, I found a bug in some of my code:
Can you spot it? I was getting a NullPointerException thrown from somewhere inside ConvertServletModule. The problem was that my contextInitialized method had,
instead of,
So when getInjector was being called from inside the implementation of super.contextInitialized, the servletContext field was still null.
I think that is a great example of why we should change this to make the API clear and explicit: you get the ServletContext passed to you in getInjector and can use it to construct the injector.
From gianmarco.gherardi on February 20, 2012 01:34:57
Any updates on this?