學習地址: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>