2011年11月18日金曜日

[Spring][hibernate][設定]xxx-servlet.xmlの記述(前半)

web.xmlにDispatcherServletの設定を記述すると、applicationContext.xmlの次に "[サーブレット名]-servlet.xml" という名前の設定ファイルをSpringが自動的に探して、設定を読み込む。

設定ファイルの読み込み順序は、次の通り。
web.xml → applicationContext.xml -> [サーブレット名]-servlet.xml

サーブレット設定のファイルでは、定義したbean間の依存関係等を記述する。
冒頭部のエンコード設定等は他の設定ファイルと同じく、Springに付属しているサンプル等からコピーする。
(この記述は、Spring3.0.2(Java1.6、Tomcat6.0)を動かしたときの設定)

<?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:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

コントローラを名前によって自動で識別させる場合は、次のように記述する。

  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

このように記述すると例えばURLに
http://localhost:8080/sample/index.html
と指定した場合、SpringフレームワークがIndexControllerというクラスを自動で探す。
LoginFormControllerのように、2つ以上の単語が複合する名前の場合、全て小文字で表記する。
http://localhost:8080/sample/loginform.html
(↑)こうURL指定すると、SpringフレームワークがLoginFormControllerというクラスを自動で探す。

DIを自動で行わせるためにDI対象のクラスを自動スキャンする設定は、次の通り。

  <context:component-scan base-package="sample.dao.impl" />

DAOインターフェイスに対応するDAO実装クラスが "sample.dao.impl" パッケージにあるとき、上記のように記述することで、同パッケージ配下の全てのクラスをDI対象として読み込む。
ただしDIに使いたいクラスの宣言部に@Componentアノテーションを付けておく必要がある。

@Complnent
public class SampleUserDaoImpl implements SampleUserDao {

DI対象として読み込まれたクラスを使いたい場合は、@Autowiredアノテーションを付けて宣言する。
例えばSampleUserDaoというインタフェースをDIで使いたい場合は、このインターフェースを使いたいクラスで次のように記述する。

@Autowired
private SampleUserDao sampleUserDao;

先にコンポーネントスキャンで、sample.dao.implパッケージ配下を読ませているので、同パッケージ配下にある実装クラスがインジェクションされる。
DAOクラスをインターフェースとしているのは、実装のDI設定を柔軟に変更できるようにするため。
例えばテストのために固定データをreturnするだけのモックをDIさせたい場合は、コンポーネントスキャンでモックのパッケージを指定する。(SampleUserDaoインターフェースの実装がモックに差し替わる)

この他、ビューや例外処理の記述もあるが、長くなりすぎるため別の記事とする。

0 件のコメント:

コメントを投稿