java web 之 struts2 与 sping 集成

struts2 与 spring 集成,只需要 struts2-spring-plugin-xxx.jar 即可;这个 struts2 官方文档中已经说明:To enable Spring integration, simply include struts2-spring-plugin-x-x-x.jar in your application.

可是为什么呢?打开 plugin 的 jar 包发现有个 struts-plugin.xml 文件;这就是 struts2 和 sping 集成只需有这个jar包就行的原因了。

具体做法:

1.  web.xml 配置监听(用spring配置各个bean对象):

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2.  applicationContext.xml 配置各个bean对象:

<beans default-autowire="autodetect">
    <bean id="personManager" class="com.acme.PersonManager"/>
    ...
</beans>

3.  struts.xml 配置关联:

 3.1 正常情况下在struts.xml里为每个action指定具体类class,当使用了spring默认的对象工厂SpringObjectFactory后,由spring默认的自动装载来指定action类和类之间的依赖关系。(摘自struts.xml官方文档之pring plugin)

  3.2  把bean完全交给spring控制,以利用spring的aop等优势技术到你的bean上,可以将你的struts.xml里的class属性只想spring的配置文件applicationContext.xml里配置的bean的name属性上去

struts.xml:

 <package name="secure" namespace="/secure" extends="default">
        <action name="bar" class="barClass">
            <result>bar.ftl</result>
        </action>
 </package>

applicationContext.xml:

<beans default-autowire="autodetect">
    <bean id="barClass" class="com.my.BarClass" singleton="false"/>
    ...
</beans>

另外:

在struts-plugin.xml 里面有这么一段话:

<bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
    
    <!--  Make the Spring object factory the automatic default -->
    <constant name="struts.objectFactory" value="spring" />

应该就是,当有超过一个对象工厂时,配置 struts.objectFactory 时:

<struts>
  <constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
  ... 
</struts>
value 字段可以是“sping” 或者 是那个具体的类(org.apache.struts2.spring.StrutsSpringObjectFactory)的原因了吧。
原文地址:https://www.cnblogs.com/sin7/p/2876352.html