学习地址:https://www.cnblogs.com/huqianliang/p/5673701.html
一、xml中属性值设定
1、直接在xml文件中使用属性值;
2、属性值在外部文件*.properties中定义,然后再引入xml中
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性driverClassName、 url、user、password --> <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> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性driverClassName、 url、user、password --> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc\:mysql\://192.168.1.90\:8066/life_schema?useUnicode\=true&characterEncoding\=utf-8" /> <property name="username" value="admin" /> <property name="password" value="123456" /> </bean>
二、Spring中xml引入外部properties文件
1、Spring中的常规实现
以前的实现
<bean id="jdbcProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:/spring/jdbc.properties</value> </list> </property> </bean>
spring推荐实现
<context:property-placeholder location="classpath:spring/jdbc.properties" />
注:<context:property-placeholder/>这个基于命名空间的配置,其实内部就是创建一个PropertyPlaceholderConfigurer Bean而已。
2、PropertyPlaceHolderConfiger解释
定义:PropertyPlaceholderConfigurer起的作用就是将占位符指向的配置信息放在bean中定义的工具。
jar来源:PropertyPlaceHolderConfiger在spring-beans jar包下
配置项:location--properties文件地址、fileEncoding--配置文件编码格式
配置单个文件
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>conf/sqlmap/jdbc.properties</value> </property> <property name="fileEncoding"> <value>UTF-8</value> </property> </bean>
配置多个文件
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/mail.properties</value> <value>classpath: conf/sqlmap/jdbc.properties</value>//注意这两种value值的写法 </list> </property> </bean>
3、Property属性加密
原理:
1、在properties文件中存储加密以后的属性值
2、新建Configer类继承PropertyPlaceHolderConfiger,重写convertProperty(String propertyName, String propertyValue) 方法,把需要解密的属性解密返回
3、在 spring-context.xml 添加引用,替换原有的 <context:property-placeholder location="... " />
<bean id="propertyConfigurer" class="com.guduo.common.encrypdecrypt.utils.EncryptPropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:activemq.properties</value> </list> </property> </bean>