Often there are Spring-related configuration options which don't belong inside the final jar/war for a Java application. Either because the options are different for each deployment environment or because the value of the option is sensitive (passwords). The PropertyPlaceholderConfigurer class attempts to remedy the management and injection of the values for these options. It reads one or more property files, optionally using system properties for defaults, and uses the values found to fill property placeholders of the form ${property name} found in the ApplicationContext in which the configurer is defined.
- Advantages:
- It provides a mechanism for externalizing configuration so that each environment can be configured differently without re-building the application.
- It provides a mechanism for injecting test properties at test-time without incurring much development overhead.
- Using the classpath:<file> pseudo-uri enables developers to easily include default properties while still allowing users to over-ride the defaults by adding the location of a properties file to the application's classpath.
- The PropertyPlaceholderConfigurer is extensible and provides a method, convertPropertyValue(String), which can be over-ridden in a sub-class to handle the encryption of properties.
- Disadvantages:
- The configurer class does not re-load at a regular interval. Changing the properties managed by the configurer requires a restart of the application using it. This can be overcome in some limited situations through a custom sub-class, but for the most part, is not really supported by the Spring container.
- Only Spring-managed beans can take advantage of these properties.
Sample
config.xml
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:project.properties</value> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> </bean>
project.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:mydb
Comments