[SSH]struts2-spring-plugin.jar瞭解

  在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類。 spring

 

假設以前的strust.xml中有以下設置:json

<action name=」CpAction」  class=」cn.ricki.cheung.action.CpAction >
<result type=」json」/>
</action>

 

如今由Spring來管理對象,在applicationContext.xml添加以下內容:app

 

<beans>
<bean id=」cpAction 」 class=」cn.ricki.cheung.action.CpAction」/>
</beans>

修改strust.xml:spa

<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內容以下:code

 

<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。xml

相關文章
相關標籤/搜索