Spring Tutorial - Spring Place Holder Properties








PropertyPlaceholderConfigurer class can externalize the deployment details into a properties file.

We can then access its value from bean configuration file via a special format: ${variable}.

The following code show show to put database connection properties in a separate file.

Database properties file

The following code create sa properties file (database.properties). It includes database connection details. We can put it into the project class path.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/java2sjava
jdbc.username=root
jdbc.password=password

The following xml configuration file use PropertyPlaceholderConfigurer to map the 'database.properties' properties file .

<bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
   <value>database.properties</value>
   </property>
</bean>

Here is the full xml configuration file.

<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.java2s.customer.dao.impl.JdbcCustomerDAO">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="customerSimpleDAO" 
                class="com.java2s.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>