我想在servlet中使用spring自动装配,所以这是我的代码:
@Configurable public class ImageServlet extends HttpServlet { @Autowired private SystemPropertyDao systemPropertyDao; @Override public void init() throws ServletException { String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER); }
而用SystemPropertyDao注释@Repository
SystemPropertyDao
@Repository
和我的applicationContext.xml:
<context:component-scan base-package="com.basepackage" /> <mvc:annotation-driven /> <context:annotation-config /> <context:spring-configured/> web.xml: <servlet> <servlet-name>imageServlet</servlet-name> <servlet-class>com.xeno.basepackage.ImageServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>imageServlet</servlet-name> <url-pattern>/myimages/*</url-pattern> </servlet-mapping>
有时自动装配有效,有时却无效(对spring bean systemPropertyDao的引用为null),有人可以告诉我是否缺少什么吗?
我在以下链接中遵循了该解决方案,并且工作正常: 从JBoss中的servlet访问Spring Bean。
public class MyServlet extends HttpServlet { @Autowired private MyService myService; public void init(ServletConfig config) { super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } }