Spring PropertyPlaceholderConfigurerの例
多くの場合、ほとんどのSpring開発者は、デプロイメントの詳細(データベースの詳細、ログファイルのパス)全体を次のようにXML Bean構成ファイルに入れます。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="customerSimpleDAO" class="com.mkyong.customer.dao.impl.SimpleJdbcCustomerDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mkyongjava"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
</beans>
しかし、企業環境では、通常、配備の詳細はシステムまたはデータベース管理者だけが知ることができ、Bean構成ファイルに直接アクセスすることを拒否し、デプロイメント構成のために別のファイルを要求します。たとえば、単純なデプロイメントの詳細のみを使用します。
PropertyPlaceholderConfigurerの例
これを修正するには、
PropertyPlaceholderConfigurer
クラスを使用して、デプロイメントの詳細をプロパティファイルに外部化し、Bean設定ファイルから特別な形式(
$ \ {variable}
)でアクセスします。
プロパティファイル(database.properties)を作成し、データベースの詳細を含め、プロジェクトクラスパスに配置します。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongjava
jdbc.username=root
jdbc.password=password
Bean設定ファイルに
PropertyPlaceholderConfigurer
を宣言し、今作成した
` database.properties
‘プロパティファイルにマップします。
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
完全な例
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="customerSimpleDAO"
class="com.mkyong.customer.dao.impl.SimpleJdbcCustomerDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>