不講前言,也無后語(yǔ),只記錄一下實(shí)現(xiàn)及注意點(diǎn)。
在servlet+spring項(xiàng)目中,想在servlet類里面注入spring bean有以下兩種方式:
1,復(fù)寫servlet的init方法,如下
注意://支持@Autowired和@Resource方式注入bean,但注入的bean只能通過注解方式實(shí)例化(context:component-scan),不能通過xml 這種方式。
@Override
?public void init() throws ServletException {
? ? super.init();
? ? WebApplicationContextUtils.getWebApplicationContext(getServletContext())
? ? .getAutowireCapableBeanFactory().autowireBean(this);
}
2,復(fù)寫servlet init(ServletConfig config)方法
注意://僅支持@Autowired方式注入bean,但不限bean實(shí)例化方式(xml <bean /> ,注解方式)
@Override
?public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
pom.xml需引入servlet及spring相關(guān)的包
javax.servlet servlet-api 3.0
org.springframework spring-core 3.1.2.RELEASE
org.springframework spring-webmvc 3.1.2.RELEASE
org.springframework spring-beans 3.1.2.RELEASE
org.springframework spring-context 3.1.2.RELEASE
org.springframework spring-aop 3.1.2.RELEASE
org.springframework spring-tx 3.1.2.RELEASE
org.springframework spring-orm 3.1.2.RELEASE
最后,如果覺得在每個(gè)servlet里面重寫init方法麻煩,可以建一個(gè)BaseServlet繼承HttpServlet復(fù)寫init方法,其他servlet繼承BaseServlet即可。

