2011年11月17日木曜日

[Spring][hibernate][applicationContext.xml][設定ファイル]Springの設定ファイル記述について

"web.xml" と同様、WEB-INF直下に "applicationContext.xml" という名前で設定ファイルを置く。
web.xml内にリスナの設定が書かれていれば、applicationContext.xmlというファイルをSpringフレームワークが自動的に探して設定を読む。

このファイルには、データソース(DB設定)等のbean設定を記述する。
ここでbeanとして定義されたものをDIで使うことができる。ファイルの冒頭では、次のように記述する。
(この記述は、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">

エンコーディングはUTF-8としている。
web.xmlのエンコーディングをShift_JISにしていても、ここはUTF-8と書いて問題ない。(動作する)
データベースがShift_JISでWebアプリはUTF-8など、開発条件・制約は様々あるので臨機応変に設定を変更する。

hibernateの設定をhibernate.cfg.xmlから読み込む場合は、次のように記述する。

  <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation">
      <value>/WEB-INF/src/hibernate.cfg.xml</value>
    </property>
  </bean>

O/Rマッピングのフレームワークとしてhibernateを単体で使う場合、hibernate.cfg.xmlをクラスパス上に置くことでhibernateは自動的にこの名前の設定ファイルを読みに行くが、Springと組み合わせて使う場合はこのように記述する。
hibernate.cfg.xmlを使わず、applicationContext.xmlに設定を書く方法もあるが、こちらはSpring独自の文法でhibernate設定を書き直さねばならない。hibernate単体の資産がある場合は、上記の書き方が推奨される。

applicationContext.xmlにsessionFactoryを定義しておくことで、DIによりどのソースコードでもSessionFactoryを取得できるようになる。SessionFactoryでopenSessionを行えば、トランザクション制御も可能になる。
Spring3以降は、SessionFactoryを使うべき位置にDIで挿入することが推奨されている。

Spring固有の設定としては、メッセージリソースの設定がある

  <!-- MessageSource -->
  <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
      <list>
        <value>messages</value>
      </list>
    </property>
  </bean>

このように記述しておくことでmessages.propertiesファイルにあるプロパティを使うことができる。
エラーメッセージ等を key=value の形式で記述しておき、keyでプロパティからvalueを取得できる。

最後に</beans>タグで設定を閉じて完了。

0 件のコメント:

コメントを投稿