Spring中配置和读取多个Properties文件

来源:互联网 发布:传智48期php就业班 编辑:程序博客网 时间:2024/05/17 09:20
public class PropertiesFactoryBeanextends PropertiesLoaderSupportimplements FactoryBean, InitializingBean

Allows for making a properties file from a classpath location available as Properties instance in a bean factory. Can be used to populate any bean property of type Properties via a bean reference.

Supports loading from a properties file and/or setting local properties on this FactoryBean. The created Properties instance will be merged from loaded and local values. If neither a location nor local properties are set, an exception will be thrown on initialization.

Can create a singleton or a new object on each request. Default is a singleton.

 

一个系统中通常会存在如下一些以Properties形式存在的配置文件

1.数据库配置文件demo-db.properties:

Properties代码  收藏代码
  1. database.url=jdbc:mysql://localhost/smaple  
  2. database.driver=com.mysql.jdbc.Driver  
  3. database.user=root  
  4. database.password=123  

 

2.消息服务配置文件demo-mq.properties:

Properties代码  收藏代码
  1. #congfig of ActiveMQ  
  2. mq.java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory  
  3. mq.java.naming.provider.url=failover:(tcp://localhost:61616?soTimeout=30000&connectionTimeout=30000)?jms.useAsyncSend=true&timeout=30000  
  4. mq.java.naming.security.principal=  
  5. mq.java.naming.security.credentials=  
  6. jms.MailNotifyQueue.consumer=5  

 

3.远程调用的配置文件demo-remote.properties:

Properties代码  收藏代码
  1. remote.ip=localhost  
  2. remote.port=16800  
  3. remote.serviceName=test  

 

一、系统中需要加载多个Properties配置文件

应用场景:Properties配置文件不止一个,需要在系统启动时同时加载多个Properties文件。

配置方式:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="  
  5.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.       
  7.     <!-- 将多个配置文件读取到容器中,交给Spring管理 -->  
  8.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  9.         <property name="locations">  
  10.            <list>  
  11.               <!-- 这里支持多种寻址方式:classpath和file -->  
  12.               <value>classpath:/opt/demo/config/demo-db.properties</value>  
  13.               <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->  
  14.               <value>file:/opt/demo/config/demo-mq.properties</value>  
  15.               <value>file:/opt/demo/config/demo-remote.properties</value>  
  16.             </list>  
  17.         </property>  
  18.     </bean>  
  19.       
  20.     <!-- 使用MQ中的配置 -->  
  21.     <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
  22.         <property name="environment">  
  23.             <props>  
  24.                 <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
  25.                 <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
  26.                 <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
  27.                 <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
  28.                 <prop key="userName">${mq.java.naming.security.principal}</prop>  
  29.                 <prop key="password">${mq.java.naming.security.credentials}</prop>  
  30.             </props>  
  31.         </property>  
  32.     </bean>  
  33. </beans>  

 我们也可以将配置中的List抽取出来:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="  
  5.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.       
  7.     <!-- 将多个配置文件位置放到列表中 -->  
  8.     <bean id="propertyResources" class="java.util.ArrayList">  
  9.         <constructor-arg>  
  10.             <list>  
  11.               <!-- 这里支持多种寻址方式:classpath和file -->  
  12.               <value>classpath:/opt/demo/config/demo-db.properties</value>  
  13.               <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->  
  14.               <value>file:/opt/demo/config/demo-mq.properties</value>  
  15.               <value>file:/opt/demo/config/demo-remote.properties</value>  
  16.             </list>  
  17.         </constructor-arg>  
  18.     </bean>  
  19.       
  20.     <!-- 将配置文件读取到容器中,交给Spring管理 -->  
  21.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  22.         <property name="locations" ref="propertyResources" />  
  23.     </bean>  
  24.       
  25.     <!-- 使用MQ中的配置 -->  
  26.     <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
  27.         <property name="environment">  
  28.             <props>  
  29.                 <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
  30.                 <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
  31.                 <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
  32.                 <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
  33.                 <prop key="userName">${mq.java.naming.security.principal}</prop>  
  34.                 <prop key="password">${mq.java.naming.security.credentials}</prop>  
  35.             </props>  
  36.         </property>  
  37.     </bean>  
  38. </beans>  

 

二、整合多工程下的多个分散的Properties

应用场景:工程组中有多个配置文件,但是这些配置文件在多个地方使用,所以需要分别加载。

配置如下:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xsi:schemaLocation="  
  6.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  7.       
  8.     <!-- 将DB属性配置文件位置放到列表中 -->  
  9.     <bean id="dbResources" class="java.util.ArrayList">  
  10.         <constructor-arg>  
  11.         <list>  
  12.             <value>file:/opt/demo/config/demo-db.properties</value>  
  13.         </list>  
  14.         </constructor-arg>  
  15.     </bean>  
  16.   
  17.     <!-- 将MQ属性配置文件位置放到列表中 -->  
  18.     <bean id="mqResources" class="java.util.ArrayList">  
  19.         <constructor-arg>  
  20.         <list>  
  21.             <value>file:/opt/demo/config/demo-mq.properties</value>  
  22.         </list>  
  23.         </constructor-arg>  
  24.     </bean>  
  25.       
  26.     <!-- 用Spring加载和管理DB属性配置文件 -->  
  27.     <bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  28.         <property name="order" value="1" />  
  29.         <property name="ignoreUnresolvablePlaceholders" value="true" />   
  30.         <property name="locations" ref="dbResources" />  
  31.     </bean>  
  32.       
  33.     <!-- 用Spring加载和管理MQ属性配置文件 -->  
  34.     <bean id="mqPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  35.         <property name="order" value="2" />  
  36.         <property name="ignoreUnresolvablePlaceholders" value="true" />   
  37.         <property name="locations" ref="mqResources" />  
  38.     </bean>  
  39.       
  40.     <!-- 使用DB中的配置属性 -->  
  41.     <bean id="rmsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"   
  42.         p:driverClassName="${demo.db.driver}" p:url="${demo.db.url}" p:username="${demo.db.username}"   
  43.         p:password="${demo.db.password}" pp:maxActive="${demo.db.maxactive}"p:maxWait="${demo.db.maxwait}"   
  44.         p:poolPreparedStatements="true" p:defaultAutoCommit="false">  
  45.     </bean>  
  46.       
  47.     <!-- 使用MQ中的配置 -->  
  48.     <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
  49.         <property name="environment">  
  50.             <props>  
  51.                 <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
  52.                 <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
  53.                 <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
  54.                 <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
  55.                 <prop key="userName">${mq.java.naming.security.principal}</prop>  
  56.                 <prop key="password">${mq.java.naming.security.credentials}</prop>  
  57.             </props>  
  58.         </property>  
  59.     </bean>  
  60. </beans>  

 注意:其中order属性代表其加载顺序,而ignoreUnresolvablePlaceholders为是否忽略不可解析的 Placeholder,如配置了多个PropertyPlaceholderConfigurer,则需设置为true。这里一定需要按照这种方式设置这两个参数。

 

三、Bean中直接注入Properties配置文件中的值

应用场景:Bean中需要直接注入Properties配置文件中的值 。例如下面的代码中需要获取上述demo-remote.properties中的值:

Java代码  收藏代码
  1. public class Client() {  
  2.     private String ip;  
  3.     private String port;  
  4.     private String service;  
  5. }  

 配置如下:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>"  
  3.  xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"  
  4.  xmlns:util="<a href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a>"  
  5.  xsi:schemaLocation="  
  6.  <href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a<href="http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</a>  
  7.  <href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a<href="http://www.springframework.org/schema/util/spring-util-3.0.xsd">http://www.springframework.org/schema/util/spring-util-3.0.xsd</a>">  
  8.    
  9.  <!-- 这种加载方式可以在代码中通过@Value注解进行注入,   
  10.  可以将配置整体赋给Properties类型的类变量,也可以取出其中的一项赋值给String类型的类变量 -->  
  11.  <!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->  
  12.  <util:properties id="remoteSettings" location="file:/opt/demo/config/demo-remote.properties" />   
  13.    
  14.  <!-- <util:properties/> 标签的实现类是PropertiesFactoryBean,  
  15.  直接使用该类的bean配置,设置其locations属性可以达到一个和上面一样加载多个配置文件的目的 -->  
  16.  <bean id="settings"   
  17.    class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  18.    <property name="locations">  
  19.   <list>  
  20.     <value>file:/opt/rms/config/rms-mq.properties</value>  
  21.     <value>file:/opt/rms/config/rms-env.properties</value>  
  22.   </list>  
  23.    </property>  
  24.  </bean>  
  25. </beans>  

 Client类中使用Annotation如下:

Java代码  收藏代码
  1. import org.springframework.beans.factory.annotation.Value;  
  2.   
  3. public class Client() {  
  4.     @Value("#{remoteSettings['remote.ip']}")  
  5.     private String ip;  
  6.     @Value("#{remoteSettings['remote.port']}")  
  7.     private String port;  
  8.     @Value("#{remoteSettings['remote.serviceName']}")  
  9.     private String service;  
  10. }  

 

四、Bean中存在Properties类型的类变量

应用场景:当Bean中存在Properties类型的类变量需要以注入的方式初始化

1. 配置方式:我们可以用(三)中的配置方式,只是代码中注解修改如下

Java代码  收藏代码
  1. import org.springframework.beans.factory.annotation.Value;  
  2. import org.springframework.beans.factory.annotation.Autowired;  
  3.   
  4. public class Client() {  
  5.     @Value("#{remoteSettings}")  
  6.     private Properties remoteSettings;  
  7. }  

 

2. 配置方式:也可以使用xml中声明Bean并且注入

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="  
  5.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  6.       
  7.     <!-- 可以使用如下的方式声明Properties类型的FactoryBean来加载配置文件,这种方式就只能当做Properties属性注入,而不能获其中具体的值 -->  
  8.     <bean id="remoteConfigs" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  9.         <property name="locations">  
  10.             <list>  
  11.                 <value>file:/opt/demo/config/demo-remote.properties</value>  
  12.             </list>  
  13.         </property>  
  14.     </bean>  
  15.       
  16.     <!-- 远端调用客户端类 -->  
  17.     <bean id="client" class="com.demo.remote.Client">  
  18.         <property name="properties" ref="remoteConfigs" />  
  19.     </bean>  
  20. </beans>  

代码如下:

Java代码  收藏代码
  1. import org.springframework.beans.factory.annotation.Autowired;  
  2.   
  3. public class Client() {  
  4.     //@Autowired也可以使用  
  5.     private Properties remoteSettings;  
  6.       
  7.     //getter setter  
  8. }  

 

上述的各个场景在项目群中特别有用,需要灵活的使用上述各种配置方式。

 

原文:http://kingxss.iteye.com/blog/1880681

 

补充:

The Spring Framework PropertiesFactoryBeanTests.java source code

复制代码
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.springframework.beans.factory.config;import java.util.Properties;import junit.framework.TestCase;import org.springframework.core.JdkVersion;import org.springframework.core.io.ClassPathResource;/** * @author Juergen Hoeller * @since 01.11.2003 */public class PropertiesFactoryBeanTests extends TestCase {    public void testWithPropertiesFile() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties"));        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("99", props.getProperty("tb.array[0].age"));    }    public void testWithPropertiesXmlFile() throws Exception {        // ignore for JDK < 1.5        if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_15) {            return;        }        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test-properties.xml"));        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("99", props.getProperty("tb.array[0].age"));    }    public void testWithLocalProperties() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        Properties localProps = new Properties();        localProps.setProperty("key2", "value2");        pfb.setProperties(localProps);        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("value2", props.getProperty("key2"));    }    public void testWithPropertiesFileAndLocalProperties() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties"));        Properties localProps = new Properties();        localProps.setProperty("key2", "value2");        localProps.setProperty("tb.array[0].age", "0");        pfb.setProperties(localProps);        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("99", props.getProperty("tb.array[0].age"));        assertEquals("value2", props.getProperty("key2"));    }    public void testWithPropertiesFileAndMultipleLocalProperties() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties"));        Properties props1 = new Properties();        props1.setProperty("key2", "value2");        props1.setProperty("tb.array[0].age", "0");        Properties props2 = new Properties();        props2.setProperty("spring", "framework");        props2.setProperty("Don", "Mattingly");        Properties props3 = new Properties();        props3.setProperty("spider", "man");        props3.setProperty("bat", "man");        pfb.setPropertiesArray(new Properties[] {props1, props2, props3});        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("99", props.getProperty("tb.array[0].age"));        assertEquals("value2", props.getProperty("key2"));        assertEquals("framework", props.getProperty("spring"));        assertEquals("Mattingly", props.getProperty("Don"));        assertEquals("man", props.getProperty("spider"));        assertEquals("man", props.getProperty("bat"));    }    public void testWithPropertiesFileAndLocalPropertiesAndLocalOverride() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties"));        Properties localProps = new Properties();        localProps.setProperty("key2", "value2");        localProps.setProperty("tb.array[0].age", "0");        pfb.setProperties(localProps);        pfb.setLocalOverride(true);        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("0", props.getProperty("tb.array[0].age"));        assertEquals("value2", props.getProperty("key2"));    }    public void testWithPrototype() throws Exception {        PropertiesFactoryBean pfb = new PropertiesFactoryBean();        pfb.setSingleton(false);        pfb.setLocation(new ClassPathResource("/org/springframework/beans/factory/config/test.properties"));        Properties localProps = new Properties();        localProps.setProperty("key2", "value2");        pfb.setProperties(localProps);        pfb.afterPropertiesSet();        Properties props = (Properties) pfb.getObject();        assertEquals("99", props.getProperty("tb.array[0].age"));        assertEquals("value2", props.getProperty("key2"));        Properties newProps = (Properties) pfb.getObject();        assertTrue(props != newProps);        assertEquals("99", newProps.getProperty("tb.array[0].age"));        assertEquals("value2", newProps.getProperty("key2"));    }}
复制代码
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 动车没有票了怎么办 12306取消订单3次怎么办 【12306取消订单3次怎么办】 火车票取消订单3次怎么办 12306收不到验证码怎么办 安逸花验证码次数限制怎么办 航班晚点导致错过转机怎么办 想去沈阳站送站怎么办 高铁没有赶上车怎么办 火车晚点赶不上下一趟车怎么办 列车晚点影响下一趟车怎么办? 高铁晚点赶不上下班车怎么办 火车在半路坏了怎么办 做火车中途坏了怎么办 员工怀孕不上班保险怎么办 怀孕带孩子不能上班保险怎么办 怀孕了不想上班保险怎么办 高铁票没票了怎么办 购买动车票无座怎么办 个税工资多报怎么办 火车晚点耽误了转车怎么办 坐火车联系不上怎么办 号码被别人注册了12306怎么办 注册12306的号码换了怎么办 12306号码被注册了怎么办 12306身份证被注册了怎么办 12306被别人注册了怎么办 铁路1236注册名忘记了怎么办 12306手机被别人注册了怎么办 12306注册手机不用了怎么办 到站后火车票掉了怎么办 在手机上买了票怎么办 智行火车票抢不到票怎么办 高铁买票票丢了怎么办 异地恋房费太贵怎么办 高铁票车上丢了怎么办 取了高铁票丢了怎么办 高铁买了学生票没带学生证怎么办 买的学生票超过区间怎么办 买了超过区间的学生票怎么办 火车票大于学生票购买区间怎么办