在bean定义时设置bean属性的值时,除了设置固定的值,还可以通过EL表达式和占位符来设置,容器在解析bean定义时会对EL表达式和占位符进行解析求值。本篇来学习一下通过占位符定义属性的用法。
占位符的取值范围有三个:系统变量(System.getProperty)、坏境变量(System.getEnv)、自定义的Properties文件。
1、PropertyPlaceholderConfigurer
一个BFPP,通过location属性把properties文件的路径传入,并且可以设置系统变量加载模式,有三种:0、不检查系统属性;1、优先加载自定义属性,加载不到时加载系统属性;2、优先加载系统属性,加载不到时再加载自定义属性。通过systemPropertiesMode设置加载模式。占位符的前后缀默认是${和},但是可以通过设置placeholderPrefix和placeholderSuffix来修改前后缀。PropertyPlaceholderConfigurer的用法如下
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/com/ningpai/web/config/jdbc.properties</value> <value>classpath:/com/ningpai/web/config/es-hosts.properties</value> <value>classpath:/com/ningpai/web/config/redis.properties</value> <value>classpath:/com/ningpai/web/config/controltask.properties</value> <value>classpath:/com/ningpai/web/config/amq.properties</value> <value>classpath:/com/ningpai/web/config/copyright.properties</value> </list> </property> <!--value="classpath:/com/ningpai/web/config/jdbc.properties" />--> <property name="ignoreUnresolvablePlaceholders" value="true"/> </bean>
只有一个配置文件时
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:/com/ningpai/web/config/jdbc.properties</value> </property> <!--value="classpath:/com/ningpai/web/config/jdbc.properties" />--> </bean>
使用时默认${}
<!-- 数据源的配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- data source configuration --> <property name="initialSize" value="10" /><!-- initial connections --> <property name="maxActive" value="50" /><!-- MAX connections --> <!--<property name="maxIdle" value="10" /><!– MAX idle connections –>--> <property name="minIdle" value="5" /><!-- MIN idle connections --> <!-- 处理mysql 8小时自动断开连接的问题 --> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="validationQuery" value="select 1" /> <property name="timeBetweenEvictionRunsMillis" value="20000" /> <property name="numTestsPerEvictionRun" value="100" /> <!--属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御SQL注入的filter:wall --> <property name="filters" value="${druid.filters}" /> <property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${jdbc.public.key}" /> </bean>