Reputation: 4965
How do I inject objects into a Servlet using Dagger?
Since the servlet container instantiates the Servlets themselves, they are not created with Dagger. Therefore, the only mechanism I can see to inject into them is via static injections, which the dagger homepage warns against doing. Is there another (best practices) way to do it?
Specifically, I am using Jetty and GWT (my servlets extend RemoteServiceServlet), but I don't think those details matter.
Upvotes: 1
Views: 1577
Reputation: 4965
While there is no stock infrastructure for this, I did the following:
I put the ObjectGraph
into the ServletContext
of the web server. Then, for each Servlet, I can do the following,
@Inject
SomeDependency dependency;
@Inject
SomeOtherDependency otherDependency;
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
((ObjectGraph) filterConfig.getServletContext().getAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH)).inject(this);
}
where I have previously defined the DaggerConstants
myself.
There are likely a variety of ways to get the ObjectGraph
into the ServletContext
, depending on what your application is. We use an embedded jetty server, so we control everything during startup. Not sure how you would do it in a general container, but presuming you instantiate your main ObjecGraph
through some init servlet, you would do it there.
servletContext.setAttribute(DaggerConstants.DAGGER_OBJECT_GRAPH, objectGraph);
Note that our application uses a single ObjectGraph for the entire application, which might not be your situation.
Upvotes: 1
Reputation: 4761
There is not (yet) any stock infrastructure code to support a Java EE servlet stack for Dagger.
That said, there are ways you could home-brew it until we get to it. If you were using it only for singletons, then you could mirror what some people are doing on android, and initialize your graph at app startup using a context listener, then use the Servlet's init() method to self-inject
It gets much trickier when you try to add scoping to requests and such - not impossible, but it requires more scaffolding.
Upvotes: 2