Spring PropertyPlaceholderConfigurer with Velocity

Part of the configuration magic is (one of several) Spring post-processors, that allows load the property file or files and refer to the values in these files inside XML configuration files. The rationale behind these is that property files are much easier to edit that possibly huge XML config file and using property values prevents repeating same value over and over again. With this approach, the following configuration:

 	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="username" value="some_user"/>
		<property name="password" value="secret"/>
	</bean>

can be written as

 	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>WEB-INF/mail.properties</value>
				<value>WEB-INF/jdbc.properties</value>
			</list>
		</property>
	</bean>

	
 	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>

 

and (in jdbc.properties)

jdbc.username=some_user
jdbc.password=secret

If you are using in the same project Velocity and want to utilize the VTL macros inside the configured values, the approach above will not work, because PropertyPlaceholderConfigurer will try to replace ALL macros in form ${something} with a value from property file – and throw exception if not found.The solution is easy: you need to switch the prefix of the PropertyPlaceholderConfigurer to something else than the default ${ and avoid conflict wih Velocity. The modified configuration could look like:

 
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="placeholderPrefix" value="#{"/>
		<property name="locations">
			<list>
				<value>WEB-INF/mail.properties</value>
				<value>WEB-INF/jdbc.properties</value>
			</list>
		</property>
	</bean>
 	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="username" value="#{jdbc.username}"/>
		<property name="password" value="#{jdbc.password}"/>
	</bean>

 
Advertisements

Comments are closed.

%d bloggers like this: