In this previous example we used util:properties to create java util.Properties instance. Spring also provides PropertyPlaceholderConfigurer class to externalize properties. It is a property resource configurer that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions. In this example we will use Property place holder to fetch database properties to configure datasource in spring configuration file.
1. Create a properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springschemajdbc.username=root
jdbc.password=root
This properties file needs to be placed in project class path.
2. Bean definition
PropertyPlaceholderConfigure bean has to define in spring configuration file and add the location properties. In the datasource bean we are using place holders instead of values.
<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="vinod" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:/environment.properties" />
</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>
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg>
<ref bean="dataSource"/>
</constructor-arg>
</bean>
<bean id="springjdbc" class="com.pretech.SpringJdbc">
<property name="template">
<ref bean="jdbctemplate"/>
</property>
</bean>
</beans>
3. Complete Example
You can download Spring PropertyPlaceholder example to see full implementation.
No comments:
Post a Comment