2011年2月5日土曜日

今更だけどStrutsとSpringの連携(設定ファイル編)

タイトル通り今更ながらStrutsとSpringの連携についてメモ。
基本は下記のサイトの受け売り。

第10回 Spring&Struts連携のベスト・プラクティスはこれだ!

web.xml (必要最小限)
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <!-- Standard Action Servlet Configuration -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>spring.autowire</param-name>
      <param-value>byName</param-value>
      <!--
        "byName" ... 名前により自動的なオブジェクトの参照を行う。
        "byType" ... クラス型により自動的なオブジェクトの参照を行う。※デフォルト値。
      -->
    </init-param>
  </servlet>

  <!-- Standard Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>
通常のStrutsでは・・・
<servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
    <param-name>config</param-name>
    <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
</servlet>
見比べて分かるように、init-paramタグの内容が異なる。
通常のStrutsでは「config」にStrutsの設定ファイルを指定しているが、Springと連携する場合は「spring.autowire」にbyNameを設定する。byTypeの場合は省略可。

struts-config.xml
<controller processorClass="org.springframework.web.struts.AutowiringRequestProcessor"/>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml"/>
</plug-in>
上記の2種類を適切な位置に設定する。
違う場所に挿入すると×マークが表示されるので注意☆

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">

  <context:component-scan base-package="examples"/>

</beans>
Springの設定ファイルであるapplicationContext.xmlには、ルートパッケージを指定します。
これにより、ルートパッケージ配下のアノテーションを検索するようですね。

0 件のコメント:

コメントを投稿