spring 配置文件属性设置默认值以及读取环境变量值
2017-03-17 09:14
573 查看
在 Spring 中为 javabean 注入属性文件中的属性值一般人都知道的,可以通过 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 引入一个属性文件,然后给 bean 指定属性的时候就可以用 ${jdbc.url} 方式赋值了。比如在 Spring 中是这样的配置:
有时候我们需要给 bean 赋上系统属性(System.getProperties() ) 中的值或环境变量(System.getenv() ) 中的值、亦或是设置默认值,根据程序所处的环境产生不同的行为,这样我们无法事先在某个 properties 文件预先设定好值的。
从org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 的 JavaDoc API 可知,它不光能从属性文件里取值,也能从系统属性,甚至是环境变量中取值。
但是默认情况下,也就是没有显示配置PropertyPlaceholderConfigurer bean时,它既不会从环境变量读取,也不会给设置默认值,所以如果在properties中找不到,就会提示无法转换数据类型等等错误。
因此,必须显示设置,如下:
<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>
相关文章推荐
- SpringBoot系列四:SpringBoot开发(改变环境属性、读取资源文件、Bean 配置、模版渲染、profile 配置)
- Spring AMQP实例 以及Spring 配置文件动态注入属性使用实战
- 通过环境变量设置WEB项目数据源(Spring)及其项目配置文件路径,动态更新数据源及项目配置
- 2、spring-boot 工程配置——配置文件详解:自定义属性、随机数、多环境配置等
- 51. spring boot属性文件之多环境配置【从零开始学Spring Boot】(
- 基于maven管理的项目中spring+mybatis配置数据源读取不到properties属性文件的问题
- Linux环境用C语言实现读取配置文件来区分产品的多个版本以及多个功能
- spring提供读取配置文件中的属性注解@Value
- 51. spring boot属性文件之多环境配置【从零开始学Spring Boot】
- spring boot 在不同环境下读取不同配置文件的一种方式
- SSH框架系列:Spring读取配置文件以及获取Spring注入的Bean
- 解决Spring配置文件无法读取properties属性问题
- SSH框架系列:Spring读取配置文件以及获取Spring注入的Bean
- 通过环境变量设置WEB项目数据源(Spring)及其项目配置文件路径,动态更新数据源及项目配置
- spring配置文件中<bean>的id和name属性区别,以及identifier和aliases
- 51. spring boot属性文件之多环境配置【从零开始学Spring Boot】
- java读取和设置配置文件中的属性参数
- 关于Spring boot中读取属性配置文件出现中文乱码的问题的解决
- spring的xml配置文件读取properties文件中的属性
- 【笔记】Spring配置文件中注册三种数据源及从属性文件中读取DB连接四要素