Loading name value pairs using PropertyPlaceholderConfigurer+bean placeholders using @Value

 

Spring PropertyPlaceholderConfigurer for loading properties.

  • Used to externalize property values from bean definitions
    -- Example when you want to define db values in Context definition

  • For injecting defining field values into a bean's attributes
Let's look at how to do it!
 
Used to externalize property values from bean definitions
 
database.properties under com/visionjava
db_username=root
db_password=password
 
 
employee-servlet.xml
<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="employeeDAO" class="com.javavision.SpringJDBC.dao.EmployeeDAOImpl">
        <property name="jdbcTemplate" ref="myJdbcTemplate"/>
    </bean>   
    
     <bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>
    
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>                
                <value>classpath:/com/visionjava/database.properties</value>                
            </list>
        </property>
    </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/employeestore" />
		<property name="username" value="${db_username}" />
		<property name="password" value="${db_password}" />
	</bean>
</beans>
 
The values for database user name and password are replaced from the property file when the context is loaded.
 
For injecting defining field values into a bean's attributes
 
userinterface.properties
userName=Talking Tom
 
 
bean definition in context file
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>                
                  <value>classpath:/com/visionjava/employee/userinterface.properties</value>
            </list>
        </property>
    </bean>
 
 
java class
public class Employee {
	@Value("${userName}")
	private String user;
}
 
Web Analytics Web Analytics