在struts2-spring-plugin.jar中有一個struts-plugin.xml,里面聲明了action類由spring工廠創建。在struts2插件文檔里,這樣寫着“The Spring Plugin works by overriding the Struts ObjectFactory to enhance the creation of core framework objects。”
這個插件重寫了struts的對象工廠,當創建一個action類時,它會根據struts的配置文件的class屬性的值與spring配置文件中的id屬性的值相匹配。如果沒有與之相匹配,將會像沒有使用這個插件前一樣創建,然后由spring自動裝配。
那時我有些不是很明白,為什么我的action類沒有寫注解@Component(‘xxAction’),還是可以被spring自動裝配。那是因為action類被struts和struts2-spring-plugin創建,再由spring自動裝配,但不由spring管理。如果我們想使用spring復雜的aop或spring其他的功能時,強烈建議將acion類注冊到spring容器中。即讓spring去創建action類。
假設之前的strust.xml中有如下設置:
<action name=”CpAction” class=”cn.ricki.cheung.action.CpAction “> <result type=”json”/> </action>
現在由Spring來管理對象,在applicationContext.xml添加如下內容:
<beans> <bean id=”cpAction ” class=”cn.ricki.cheung.action.CpAction”/> </beans>
修改strust.xml:
<action name=”CpAction” class=”cpAction “> <result type=”json”/> </action>
注意上面黑體顯示的部分,在struts.xml中class屬性的值為Spring配置文件中某bean id的值,它告訴 Struts2向Spring獲取id為cpAction的bean。
其實在上面提到的struts.xml中不只一個Action,除了CpAction外,還有很多,但那些我並沒有修改,而程序依然可以運行,原因看下面。
假如struts.xml內容如下:
<action name=”LabelAction” class=”cn.ricki.cheung.action.LabelAction”> <result type=”json”/> </action> <action name=”CpAction” class=”cpAction “> <result type=”json”/> </action>
當客戶端發送請求並由LabelAction處理時,Struts首先向Spring索取id為 cn.ricki.cheung.action.LabelAction的bean,但Spring配置文件中並沒有這個id的bean,這 時,Spring試着創建cn.ricki.cheung.action.LabelActio對象,並返回給Struts。