`

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

 
阅读更多

原文:http://blog.sina.com.cn/s/blog_6940cab30101evjf.html

一个系统中通常会存在如下一些以Properties形式存在的配置文件
1.数据库配置文件demo-db.properties:
Properties代码  
database.url=jdbc:mysql://localhost/smaple  
database.driver=com.mysql.jdbc.Driver  
database.user=root  
database.password=123  
 
2.消息服务配置文件demo-mq.properties:
Properties代码  
#congfig of ActiveMQ  
mq.java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory  
mq.java.naming.provider.url=failover:(tcp://localhost:61616?soTimeout=30000&connectionTimeout=30000)?jms.useAsyncSend=true&timeout=30000  
mq.java.naming.security.principal=  
mq.java.naming.security.credentials=  
jms.MailNotifyQueue.consumer=5  
 
3.远程调用的配置文件demo-remote.properties:
Properties代码  
remote.ip=localhost  
remote.port=16800  
remote.serviceName=test  
 
一、系统中需要加载多个Properties配置文件
应用场景:Properties配置文件不止一个,需要在系统启动时同时加载多个Properties文件。
配置方式:
Xml代码  
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      
    <!-- 将多个配置文件读取到容器中,交给Spring管理 -->  
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
           <list>  
              <!-- 这里支持多种寻址方式:classpath和file -->  
              <value>classpath:/opt/demo/config/demo-db.properties</value>  
              <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->  
              <value>file:/opt/demo/config/demo-mq.properties</value>  
              <value>file:/opt/demo/config/demo-remote.properties</value>  
            </list>  
        </property>  
    </bean>  
      
    <!-- 使用MQ中的配置 -->  
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
        <property name="environment">  
            <props>  
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
                <prop key="userName">${mq.java.naming.security.principal}</prop>  
                <prop key="password">${mq.java.naming.security.credentials}</prop>  
            </props>  
        </property>  
    </bean>  
</beans>  
 我们也可以将配置中的List抽取出来:
Xml代码  
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      
    <!-- 将多个配置文件位置放到列表中 -->  
    <bean id="propertyResources" class="java.util.ArrayList">  
        <constructor-arg>  
            <list>  
              <!-- 这里支持多种寻址方式:classpath和file -->  
              <value>classpath:/opt/demo/config/demo-db.properties</value>  
              <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->  
              <value>file:/opt/demo/config/demo-mq.properties</value>  
              <value>file:/opt/demo/config/demo-remote.properties</value>  
            </list>  
        </constructor-arg>  
    </bean>  
      
    <!-- 将配置文件读取到容器中,交给Spring管理 -->  
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations" ref="propertyResources" />  
    </bean>  
      
    <!-- 使用MQ中的配置 -->  
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
        <property name="environment">  
            <props>  
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
                <prop key="userName">${mq.java.naming.security.principal}</prop>  
                <prop key="password">${mq.java.naming.security.credentials}</prop>  
            </props>  
        </property>  
    </bean>  
</beans>  
 
二、整合多工程下的多个分散的Properties
应用场景:工程组中有多个配置文件,但是这些配置文件在多个地方使用,所以需要分别加载。
配置如下:
Xml代码  
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      
    <!-- 将DB属性配置文件位置放到列表中 -->  
    <bean id="dbResources" class="java.util.ArrayList">  
        <constructor-arg>  
        <list>  
            <value>file:/opt/demo/config/demo-db.properties</value>  
        </list>  
        </constructor-arg>  
    </bean>  
  
    <!-- 将MQ属性配置文件位置放到列表中 -->  
    <bean id="mqResources" class="java.util.ArrayList">  
        <constructor-arg>  
        <list>  
            <value>file:/opt/demo/config/demo-mq.properties</value>  
        </list>  
        </constructor-arg>  
    </bean>  
      
    <!-- 用Spring加载和管理DB属性配置文件 -->  
    <bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="order" value="1" />  
        <property name="ignoreUnresolvablePlaceholders" value="true" />   
        <property name="locations" ref="dbResources" />  
    </bean>  
      
    <!-- 用Spring加载和管理MQ属性配置文件 -->  
    <bean id="mqPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="order" value="2" />  
        <property name="ignoreUnresolvablePlaceholders" value="true" />   
        <property name="locations" ref="mqResources" />  
    </bean>  
      
    <!-- 使用DB中的配置属性 -->  
    <bean id="rmsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"   
        p:driverClassName="${demo.db.driver}" p:url="${demo.db.url}" p:username="${demo.db.username}"   
        p:password="${demo.db.password}" pp:maxActive="${demo.db.maxactive}"p:maxWait="${demo.db.maxwait}"   
        p:poolPreparedStatements="true" p:default>  
    </bean>  
      
    <!-- 使用MQ中的配置 -->  
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate">  
        <property name="environment">  
            <props>  
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop>  
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop>  
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop>  
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop>  
                <prop key="userName">${mq.java.naming.security.principal}</prop>  
                <prop key="password">${mq.java.naming.security.credentials}</prop>  
            </props>  
        </property>  
    </bean>  
</beans>  
 注意:其中order属性代表其加载顺序,而ignoreUnresolvablePlaceholders为是否忽略不可解析的 Placeholder,如配置了多个PropertyPlaceholderConfigurer,则需设置为true。这里一定需要按照这种方式设置这两个参数。
 
三、Bean中直接注入Properties配置文件中的值
应用场景:Bean中需要直接注入Properties配置文件中的值 。例如下面的代码中需要获取上述demo-remote.properties中的值:
Java代码  
public class Client() {  
    private String ip;  
    private String port;  
    private String service;  
}  
 配置如下:
Xml代码  
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>"  
 xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"  
 xmlns:util="<a href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a>"  
 xsi:schemaLocation="  
 <a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a> <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>  
 <a href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a> <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>">  
   
 <!-- 这种加载方式可以在代码中通过@Value注解进行注入,   
 可以将配置整体赋给Properties类型的类变量,也可以取出其中的一项赋值给String类型的类变量 -->  
 <!-- <util:properties/> 标签只能加载一个文件,当多个属性文件需要被加载的时候,可以使用多个该标签 -->  
 <util:properties id="remoteSettings" location="file:/opt/demo/config/demo-remote.properties" />   
   
 <!-- <util:properties/> 标签的实现类是PropertiesFactoryBean,  
 直接使用该类的bean配置,设置其locations属性可以达到一个和上面一样加载多个配置文件的目的 -->  
 <bean id="settings"   
   class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
   <property name="locations">  
  <list>  
    <value>file:/opt/rms/config/rms-mq.properties</value>  
    <value>file:/opt/rms/config/rms-env.properties</value>  
  </list>  
   </property>  
 </bean>  
</beans>  
 Client类中使用Annotation如下:
Java代码  
import org.springframework.beans.factory.annotation.Value;  
  
public class Client() {  
    @Value("#{remoteSettings['remote.ip']}")  
    private String ip;  
    @Value("#{remoteSettings['remote.port']}")  
    private String port;  
    @Value("#{remoteSettings['remote.serviceName']}")  
    private String service;  
}  
 
四、Bean中存在Properties类型的类变量
应用场景:当Bean中存在Properties类型的类变量需要以注入的方式初始化
1. 配置方式:我们可以用(三)中的配置方式,只是代码中注解修改如下
Java代码  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.beans.factory.annotation.Autowired;  
  
public class Client() {  
    @Value("#{remoteSettings}")  
    private Properties remoteSettings;  
}  
 
2. 配置方式:也可以使用xml中声明Bean并且注入
Xml代码  
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      
    <!-- 可以使用如下的方式声明Properties类型的FactoryBean来加载配置文件,这种方式就只能当做Properties属性注入,而不能获其中具体的值 -->  
    <bean id="remoteConfigs" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
        <property name="locations">  
            <list>  
                <value>file:/opt/demo/config/demo-remote.properties</value>  
            </list>  
        </property>  
    </bean>  
      
    <!-- 远端调用客户端类 -->  
    <bean id="client" class="com.demo.remote.Client">  
        <property name="properties" ref="remoteConfigs" />  
    </bean>  
</beans>  
代码如下:
Java代码  
import org.springframework.beans.factory.annotation.Autowired;  
  
public class Client() {  
    //@Autowired也可以使用  
    private Properties remoteSettings;  
      
    //getter setter  
}  
上述的各个场景在项目群中特别有用,需要灵活的使用上述各种配置方式。
分享到:
评论

相关推荐

    Spring中配置和读取多个Properties文件的方式方法

    在Spring框架中,配置和读取多个Properties文件是常见的需求,尤其在大型系统中,不同模块的配置往往被拆分到不同的文件中以保持代码的整洁性和可维护性。本篇文章将详细介绍如何在Spring中实现这一功能。 首先,让...

    Spring加载配置和读取多个Properties文件的讲解

    Spring加载配置和读取多个Properties文件的讲解 Spring是一款功能强大且广泛应用的Java框架,它提供了很多实用的功能和工具来帮助开发者快速构建强大且灵活的应用程序。其中一个非常重要的功能就是 Properties ...

    Spring Boot多模块配置文件读取

    在Spring Boot应用中,多模块配置文件的读取是一个重要的实践,它有助于提高代码的可维护性和模块化。本文将详细探讨如何在Spring Boot的多模块项目中管理和使用不同的配置文件,以实现低耦合的设计。 首先,了解...

    spring读取properties

    值得注意的是,可以配置多个文件路径,用以实现更灵活的配置管理。 #### 2. **创建Properties文件** 接下来,在项目的src目录下创建Properties文件,如`db.properties`。在这个文件中,你可以定义各种键值对,例如...

    spring读取配置文件

    假设你有一个复杂的项目结构,配置文件分散在多个目录下,你可以创建一个主配置文件,然后在这个主配置文件中通过`import`元素来引用其他目录的配置文件。例如,你可以在`/config/main-config.xml`中写入如下内容: ...

    java读取properties配置文件

    在Java编程中,`properties`文件是一种常用的存储配置信息的方式,它以键值对的形式组织数据,便于程序在运行时动态获取和修改配置。本文将详细介绍如何在Java中读取`properties`配置文件。 首先,我们需要了解`...

    SSM 读取properties文件

    在实际项目中,可能会有多个properties文件,比如`database.properties`、`email.properties`等,这时可以通过`locations`属性一次性加载多个文件: ```xml &lt;bean id="propertyConfigurer" class="org.spring...

    java读取.properties配置文件的几种方法

    总结来说,Java提供了多种方式来读取`.properties`配置文件,包括标准库中的`Properties`和`ResourceBundle`,以及NIO、Spring框架和第三方库如Apache Commons Configuration。选择哪种方式取决于你的具体需求,如...

    spring mvc 读取配置文件

    这篇博客“spring mvc 读取配置文件”将深入探讨如何在Spring MVC中读取和使用配置文件,以及相关工具的应用。 首先,Spring MVC中的配置文件通常是指XML配置文件,如`applicationContext.xml`或`servlet-context....

    SpringBoot第 5 讲:SpringBoot+properties配置文件读取

    SpringBoot支持多个环境的配置,通过`spring.profiles.active`属性指定当前环境。例如,你可以创建`application-dev.properties`和`application-prod.properties`,分别对应开发和生产环境。当切换`active` profile...

    Spring用代码来读取properties文件实例解析

    这样,我们可以读取多个Properties文件中的值。 结论 在本文中,我们讨论了如何使用Spring框架来读取Properties文件,并将其封装成一个工具类,以便于在Spring应用程序中使用。我们可以使用@Value注解、...

    读取以及修改properties文件

    - 如Apache Commons Configuration或Spring框架都提供了更高级的Properties文件处理功能,支持更复杂的配置结构和动态更新。 总结来说,Java中的Properties文件是配置管理的关键组件。通过`java.util.Properties`...

    java实现properties文件读取

    Java的Properties文件还支持国际化,可以为不同语言创建多个文件,如`messages_en.properties`(英语)和`messages_fr.properties`(法语)。使用`ResourceBundle`类可以轻松地切换不同语言的配置。 5. **保存修改...

    17 Spring IoC容器如何读取多个属性文件或者配置文件?慕课专栏(1)1

    当涉及到配置管理时,Spring提供了强大的能力来读取和处理多个属性文件,以便将这些配置信息注入到bean中。在不同的Spring版本中,加载多个属性文件的方法有所不同。以下是针对不同版本Spring加载多个属性文件的详细...

    Spring配置三种数据源及从属性文件中读取DB连接四要素

    对于多个数据源的情况,Spring提供`AbstractRoutingDataSource`作为基础,它可以根据某种策略动态切换数据源。下面是一个使用两个数据源的例子: 1. 创建两个具体的数据源(例如:dataSourceMaster 和 ...

    spring无法读取properties文件数据问题详解

    Spring 无法读取 properties ...Spring 无法读取 properties 文件数据问题可能是由于配置文件路径不正确、配置文件不存在或多个配置文件导致的。通过正确配置配置文件的路径和加载所有的配置文件,可以解决这些问题。

    用enum实现单例模式的方法来读取配置文件

    在实际开发中,根据项目需求,还可以考虑使用Spring框架的`@ConfigurationProperties`注解来绑定配置文件,实现更强大的类型安全和属性映射功能。不过,对于简单的配置管理,枚举单例模式已经足够实用。

    Spring PropertyPlaceholderConfigurer配置文件加载器集成ZooKeeper来实现远程配置读取

    在Spring中,`PropertyPlaceholderConfigurer`是一个非常重要的类,它用于处理属性文件中的占位符,将它们替换为实际的值。这在配置管理中起到了关键作用,特别是在大型分布式系统中,动态配置管理变得尤为重要。...

    spring,配置文件从属性文件读取JDBC连接的相关参数

    在Spring框架中,配置文件是实现依赖注入和管理应用程序组件的核心。当涉及到数据库操作时,Spring提供了从属性文件中读取JDBC连接参数的功能,这样可以使得配置更加灵活且易于维护。这篇博客“spring,配置文件从...

    java读取配置文件

    在Java编程中,读取配置文件是常见的任务,特别是在开发需要灵活配置的系统时。配置文件通常用于存储应用程序的设置,如数据库连接信息、服务器端口、第三方服务的API密钥等,这些信息可能需要根据不同的环境或需求...

Global site tag (gtag.js) - Google Analytics