Servlet+spring 在servlet中注入spring bean

不講前言,也無后語(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即可。


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容