Best/most clean way to inject dependencies into Servlets without any frameworks
What is the best way to inject dependencies into Servlets when you don't want to use any sort of DI frameworks? Shall I put them into the ServletContext
in a Se开发者_Python百科rvletContextListener
?
Yes. You could initialize them in a ServletContextListener
(if you need them pre-initialized) and then put them into the ServletContext
for all your servlets to access.
It's probably best to store the objects by their class name so retrieval is type-safe.
Foo foo = servletContext.getAttribute(Foo.class.getName());
To inject something in servlets, you need to get the servlet instances in another class. And you can't do that, because the getServlet(name)
method is deprecated (and not working).
So each servlet will have to register itself manually in the context. In the init()
method of each servlet you can add itself to a collection in the servlet context:
((List<HttpServlet>) servletContext.getAttribute("servlets")).add(this);
Then, in a ServletContextListener
you can loop all registered servlets and invoke some setters, or user reflection, to externally set the dependencies.
But..that seems too complicates, so you might stick with the new
operator here and there.
精彩评论