from the app-context.xml:
Spring is atowiring your bean correctly, the problem is that servlet container instantiates your servlet independently of spring. So you basically have two different instances - one created by spring and another created by container.
One workaround is to use ServletContextAttributeExporter
, by putting the following in your app-context.xml:
<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
<property name="attributes">
<map>
<entry key="userDao">
<ref bean="userDao"/>
</entry>
</map>
</property>
and then, in your servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
UserDao userDao = (UserDao)getServletContext().getAttribute("userDao");
// do something with userDao
PrintWriter writer = response.getWriter();
writer.write("hello");
}
another is to access the WebApplicationContext
directly:
protected void doGet(HttpServletRequest reqest, HttpServletResponse response)
throws ServletException, IOException {
WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserDao userDao =(UserDao)springContext.getBean("userDao");
}
... or simply use Spring MVC and let it autowire everything like it should.
Also see this blog post. It might be easier to convert your servlet to HttpRequestHandler
and let it be served by HttpRequestHandlerServlet
, both provided by spring.