Pages

Thursday, June 10, 2010

How to Configure Spring beans.xml File: The Use ofPropertyPlaceholderConfigurer



The file "beans.xml" used for you application is already a kind of configuration file. However, this file is designed for the developer who can quickly customize the application with less coding changes. It is not recommended for an end user to change the file.

For example, you can, of course, define the database connection properties in the beans.xml file straight away. This way, every time a user wants the application to connect to a database at a different location, the beans.xml file needs to be modified. For a complicated application, the file can grow very complicated as well. Therefore, making changes to the beans.xml file directly may not seem obvious to the end user.

Fortunately, Spring have already come up with a solution for this problem. You can define the properties in the "beans.xml" file with place holders and use the Spring provided bean PropertyPlaceholderConfigurer to replace the place holders with the value from a properties file. Here is an example of the use of PropertyPlaceholderConfigurer.

In the example from the above link, it specifies one location for the properties file with a classpath: "classpath:com/foo/jdbc.properties". In addition to that, you can also specify a file on your file system. When using a file on file system, remember to add "file:/" to an absolute path; otherwise, Spring will treat it as a relative path even the value starts with "/".

PropertyPlaceholderConfigurer also allows you to define some default values using the property "properties". The following is an example of using the default values if the file defined by "locations" property does not exist. Please note setting "ignoreResourceNotFound" to true is necessary. If not set, the application will throw exception if the defined property does not exist even we've defined the default values.

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="ignoreResourceNotFound" value="true" />
  <property name="locations">
    <value>file:///etc/app/jdbc.properties</value>
  </property>
  <property name="properties">
    <props>
      <prop key="jdbc.driverClassName">com.mysql.jdbc.Driver</prop>
      <prop key="jdbc.url">jdbc:mysql://localhost:3306/mytechtip</prop>
      <prop key="jdbc.username">jdbc_username</prop>
      <prop key="jdbc.password">xxx</prop>
    </props>
  </property>
  
</bean>

<bean id="dataSource" destroy-method="close" 
    class="org.apache.commons.dbcp.BasicDataSource">
  <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>

No comments:

Post a Comment