在 Spring 中为 javabean 注入属性文件中的属性值一般人都知道的,可以通过 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 引入一个属性文件,然后给 bean 指定属性的时候就可以用 ${jdbc.url} 方式赋值了。比如在 Spring 中是这样的配置:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> </bean>
有时候我们需要给 bean 赋上系统属性(System.getProperties() ) 中的值或环境变量(System.getenv() ) 中的值、亦或是设置默认值,根据程序所处的环境产生不同的行为,这样我们无法事先在某个 properties 文件预先设定好值的。
从org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 的 JavaDoc API 可知,它不光能从属性文件里取值,也能从系统属性,甚至是环境变量中取值。
但是默认情况下,也就是没有显示配置PropertyPlaceholderConfigurer bean时,它既不会从环境变量读取,也不会给设置默认值,所以如果在properties中找不到,就会提示无法转换数据类型等等错误。
因此,必须显示设置,如下:
<
bean
id
=
"propertyConfigurer"
class
=
"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
/>
<!-- 配置redis 缓存服务器 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.ip:127.0.0.1}" /> <property name="port" value="${redis.port:6379}" /> <property name="password" value="${redis.password:Ld123123}" /> </bean>
<bean id="routeRabbitMQConnectionFactory" class="com.ld.net.rabbitmq.MutiConnectionFactory"> <property name="mutiAddress"> <list> <value>outerMQ:5672</value> </list> </property> <property name="username" value="${RABBITMQ_USER}" /> <property name="password" value="${RABBITMQ_PWD}" /> <!-- <property name="password" value="ldld!@#$%" /> --> <property name="virtualHost" value="${OUTERMQ_VHOST}" /> <property name="automaticRecoveryEnabled" value="true" /> </bean>