Pages

Tuesday, June 18, 2013

Spring properties place holder configurer example

Often we need to put configuration parameters independently to the code. Because you do not need to lookup the code in order to configure the system and it allows to maintain the system without much trouble.  In such cases it is good to keep a properties file. A good example of the usage of this is, configuration properties of a database.

Now this can be achieved in several methods. One is to use spring's PropertiesLoaderUtils class. Another is to use the spring properties place holder configurer.

Now lets see how you can achieve this using spring properties place holder configurer.

create a database.properties file in your classpath and put the following properties in it.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/dbname
jdbc.username=root
jdbc.password=password


Then you need to declare the bean as following PropertyPlaceholderConfigurer

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>database.properties</value>
  </property>
</bean>

Now you can access the values of the properties as following.

<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>

Now what you need to access these properties in your java code too.

then you can simply use @value annotation. something like @Value("${valueKey}")


No comments:

Post a Comment