spring整合struts2 關於action bean的配置

struts2和spring的整合,關鍵點在於struts2中的action要納入spring容器的管理中成爲一個bean。 
可以在struts2中配置: 
<struts> 
    <constant name="struts.objectFactory" value="spring" /> 
</struts> 
同時action的配置class='beanID',訪問該Action時,會通過class對應值去spring中尋找相同id值的bean。 
也可以複製struts2-spring-plugin-x-x-x.jar到WEB-INF/lib目錄下。 
在struts2-spring-plugin-x-x-x.jar中有一個struts-plugin.xml配置文件,該配置文件配置內容: 
<struts> 
    <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" /> 
    <constant name="struts.class.reloading.watchList" value="" /> 
    <constant name="struts.class.reloading.acceptClasses" value="" /> 
    <constant name="struts.class.reloading.reloadConfig" value="false" /> 


    <package name="spring-default"> 
        <interceptors> 
            <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> 
            <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/> 
        </interceptors> 
    </package>    
</struts> 
可以看出該spring插件的作用就是關聯struts action和spring bean,在struts中就不必再配置 <constant name="struts.objectFactory" value="spring" />了。 


1,action的class值應等於spring中的bean id值,實現關聯,action由spring創建。 
2,若查不到,則由該spring插件根據class的值創建action,並把該action賦給spring託管,在這種情況下action的創建不是由struts2完成,而是由插件完成,並且插件擁有把action納入spring容器管理的功能,此時spring配置文件中可以不必配置action的bean了。 


兩種方式都使得action成爲了spring中的一個bean實例。 


所以,class既可以爲beanId,也可以爲類路徑,當尋找到對應bean時可以直接作爲bean訪問,若尋找不到,則會由插件根據class類路徑負責創建action實例並送給spring成爲其管理的一個bean。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章