Reputation: 3867
I can't seem to get my servlet's fields to @AutoWire; they end up null. I have a pure annotation-configured webapp (no XML files). My servlet looks like this:
@WebServlet("/service")
public
class
SatDBHessianServlet
extends HttpServlet
{
@Autowired protected NewsItemDAO mNewsItemDAO;
}
Other @AutoWired things seem to work fine, both @Service objects and @Repository objects. But not this one, and I can't figure out why. I even tried adding its package to the ComponentScan(basePackages) list for my other classes.
Additional Info:
I added the following to my servlet’s init() method, and everything seemed to wire up properly, but I'm confused as to why Spring can't wire it up without that.
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, inConfig.getServletContext());
Upvotes: 3
Views: 2597
Reputation: 19533
Servlet are web components that are not being created by Spring container, based on that lifecycle is not managed by the container and a lot of stuff that spring provides such as autowired or aspect can not run from them.
You need to indicate to the spring container that a component was created outside of IoC container and need to be part of it.
And as the API said SpringBeanAutowiringSupport is for:
Convenient base class for self-autowiring classes that gets constructed within a Spring-based web application
This generic servlet base class has no dependency on the Spring ApplicationContext concept.
There is another way to indicate servlets being created by spring container using an interface
Upvotes: 4
Reputation: 64011
Spring MVC uses the DispatcherServlet
for handling all requests in a Servlet environment.
The DispatcherServlet accordingly forwards the requests to the appropriate @Controller
class (if any) based on the @RequestMapping
on that class and/or it's methods.
What is happening in your Servlet is that it is not managed by Spring (but by the Servlet container) and there for no injection of dependencies is occurring.
Upvotes: 1