有2种集成方案
在web.xml文件中配置ContextLoaderListener,让Web Server在启动的时候将
BeanFactory放到ServletContext中
<!--可以不用配置默认去找/WEB-INF/applicationContext.xml文件-->
<context-param>
<!-- 固定名称来告诉spring的配置文件-->
<param-name>contextConfigLocation</param-name>
<!-- 可以采用/WEB-INF/applicationContext.xml的形式-->
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
第一种:
1、在Action中采用WebApplicationContextUtils.getRequiredWebApplicationContext()从ServletContext
中取得BeanFactory
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
UserManager userManager = (UserManager)factory.getBean("userManager");
2、通过BeanFactory从IoC容器中取得业务逻辑对象
存在缺点:
因为Action中出现了依赖查找,所以Action依赖Spring的API
进一步了解依赖查找和依赖注入
第二种:
1、对第一种进行改进,主要就是要将Action交给Spring来管理,创建
2、struts-config.xml文件中<action>标签的type属性需要更改为Spring的代理Action类:org.springframework.web.struts.DelegatingActionProxy
代理Action的作用:取得BeanFactory,然后到IoC容器中将本次请求对应的Action取出
3、将Action交给Spring创建,必须配置业务逻辑对象,注入给Action
<bean name="/login" class="com.bjpowernode.usermgr.web.actions.LoginAction">
<property name="userManager" ref="userManager"/>
</bean>
* 必须使用name属性,而且name属性的值必须和struts-config.xml文件中<action>标签的path属性值一致
* 必须配置业务逻辑对象
* 建议将scope设置为prototype,这样struts的Action将是线程安全的