开发者

How can I assign some spring property values from outside

开发者 https://www.devze.com 2023-01-31 11:59 出处:网络
I want to externalize the values of some valraibles in my application which uses sp开发者_开发技巧ring to something like a properties file.

I want to externalize the values of some valraibles in my application which uses sp开发者_开发技巧ring to something like a properties file.

How can I achieve this?


Spring provides a BeanFactoryPostProcessor called PropertyPlaceholderConfigurer for this purpose.

Here's an example:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:jdbc.properties"/>
</bean>

<bean id="dataSource" destroy-method="close"
    class="org.apache.commons.dbcp.BasicDataSource">
  <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>

In your classpath place a file called jdbc.properties as shown

jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost/default
jdbc.username=sa
jdbc.password=sa

When the spring context is created each value passed in ${..} is considerd as a key and values is looked at the PropertyPlaceholderConfigurer bean. If the key is not present then it throws an exception. If you don't want the exception to be thrown set the property ignoreUnresolvablePlaceholders to true, then if the key is not found then the value is as the key itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消