当前位置:编程学习 > JAVA >>

Spring强制向servlet中注入bean的方法

<!-- xml配置中将service注入到servlet中 -->
<!-- 此处testService是一个已配置的bean -->

<bean id="testServlet" class="com.test.testServlet">
<property name="testService" ref="testService"></property>

</bean>

 


/**
*然后在servlet里面得到spring注入的service

* 强制获得spring注入的service。不能直接new。需要强制得到。
*/
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
TestService testService = (TestService) applicationContext.getBean("testService");

 

 

//企图直接new或者让spring按正常方法装配都会在调用getHibernateTemplate等方法时出现nullpointer错误

//done

 

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,