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

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

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

database.url=jdbc:mysql://localhost/smaple
database.driver=com.mysql.jdbc.Driver
database.user=root
database.password=123 

2.消息服务配置文件demo-mq.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:

remote.ip=localhost
remote.port=16800
remote.serviceName=test 

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

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

配置方式:

<?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 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 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:defaultAutoCommit="false">
  </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中的值:

public class Client() {
  private String ip;
  private String port;
  private String service;
} 

配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="<a href="http://www.springframework.org/schema/beans" rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/beans</a>"
 xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance" rel="external nofollow" >http://www.w3.org/2001/XMLSchema-instance</a>"
 xmlns:util="<a href="http://www.springframework.org/schema/util" rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/util</a>"
 xsi:schemaLocation="
 <a href="http://www.springframework.org/schema/beans" rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/beans</a> <a href="http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" rel="external nofollow" >http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</a>
 <a href="http://www.springframework.org/schema/util" rel="external nofollow" rel="external nofollow" >http://www.springframework.org/schema/util</a> <a href="http://www.springframework.org/schema/util/spring-util-3.0.xsd" rel="external nofollow" >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如下:

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. 配置方式:我们可以用(三)中的配置方式,只是代码中注解修改如下

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 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>

代码如下:

import org.springframework.beans.factory.annotation.Autowired; 

public class Client() {
  //@Autowired也可以使用
  private Properties remoteSettings; 

  //getter setter
}

 五、使用通配符加载多个properties文件

<context:property-placeholder location="file:///${CONFIG_PATH}/*.properties" />

或者

<context:property-placeholder location="classpath*:/*.properties"/>

上述的各个场景在项目群中特别有用,需要灵活的使用上述各种配置方式。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Spring加载properties文件的方法

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源代码,这样更加方便.在Spring中也可以这么做,而且Spring有两种加载properties文件的方式:基于xml方式和基于注解方式. 下面分别讨论下这两种方式. 1. 通过xml方式加载properties文件         我们以Spring实例化dataSource为例,我们

  • Spring中属性文件properties的读取与使用详解

    Spring中属性文件properties的读取与使用详解 实际项目中,通常将一些可配置的定制信息放到属性文件中(如数据库连接信息,邮件发送配置信息等),便于统一配置管理.例中将需配置的属性信息放在属性文件/WEB-INF/configInfo.properties中. 其中部分配置信息(邮件发送相关): #邮件发送的相关配置 email.host = smtp.163.com email.port = xxx email.username = xxx email.password = xxx

  • 谈谈Spring 注入properties文件总结

    spring提供了多种方式来注入properties文件,本文做一个简单的总结. 在Spring配置文件中引入 方式一 通过<context:property-placeholder />标签 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • 详解Spring mvc的web.xml配置说明

    在说明web.xml配置之前我们先来了解一下需要配置的配置项的作用. 1.监听器(listener) 事件监听,js里应用广泛,各种事件函数的实现,Android和java se也是广泛的应用,各种点击事件的监听.当触发某个事件时,会触发监听在该事件上的所有监听器.spring 的 org.springframework.web.context.ContextLoaderListener 就是实现了 ServletContextListener 接口的监听器,该监听器会在容器(tomcat,je

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

    一个系统中通常会存在如下一些以Properties形式存在的配置文件 1.数据库配置文件demo-db.properties: database.url=jdbc:mysql://localhost/smaple database.driver=com.mysql.jdbc.Driver database.user=root database.password=123 2.消息服务配置文件demo-mq.properties: #congfig of ActiveMQ mq.java.namin

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

    一个系统中通常会存在如下一些以Properties形式存在的配置文件 1.数据库配置文件demo-db.properties: database.url=jdbc:mysql://localhost/smaple database.driver=com.mysql.jdbc.Driver database.user=root database.password=123 2.消息服务配置文件demo-mq.properties: #congfig of ActiveMQ mq.java.namin

  • thinkPHP中配置的读取与C方法详解

    本文实例讲述了thinkPHP中配置的读取与C方法.分享给大家供大家参考,具体如下: 1.项目公共配置 Conf/config.php 内容如下 <?php /** *项目公共配置 *@package *@author **/ return array( 'LOAD_EXT_CONFIG' => 'db,info,email,safe,upfile,cache,route,app,alipay,sms,platform,store,pay', 'APP_AUTOLOAD_PATH' =>

  • 一文详解Spring加载properties文件的方式

    目录 一.druid的资源配置管理 二.c3p0资源配置管理 三.加载properties文件 不加载系统属性 加载多个properties文件 加载所有properties文件 加载properties文件标准格式 从类路径或jar包中搜索并加载properties文件 spring第三方资源配置管理 DruidDataSource ComboPooledDataSource 一.druid的资源配置管理 导入druid的坐标: <dependency> <groupId>com

  • SpringBoot四种读取properties文件的方式(小结)

    前言 在项目开发中经常会用到配置文件,配置文件的存在解决了很大一份重复的工作.今天就分享四种在Springboot中获取配置文件的方式. 注:前三种测试配置文件为springboot默认的application.properties文件 #######################方式一######################### com.zyd.type3=Springboot - @ConfigurationProperties com.zyd.title3=使用@Configura

  • Java读取Properties文件几种方法总结

    使用J2SE API读取Properties文件的六种方法 1.使用Java.util.Properties类的load()方法 示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); p.load(in); 2.使用java.util.ResourceBundle类的getBundle()方法 示例: ResourceBundle rb

  • Spring中bean的初始化和销毁几种实现方式详解

    Bean的生命周期 : 创建bean对象 – 属性赋值 – 初始化方法调用前的操作 – 初始化方法 – 初始化方法调用后的操作 – --- 销毁前操作 – 销毁方法的调用. [1]init-method和destroy-method 自定义初始化方法和销毁方法两种方式:xml配置和注解. ① xml配置 <bean id="person" class="com.core.Person" scope="singleton" init-meth

  • java加载properties文件的六种方法总结

    java加载properties文件的六种方法总结 java加载properties文件的六中基本方式实现 java加载properties文件的方式主要分为两大类:一种是通过import java.util.Properties类中的load(InputStream in)方法加载: 另一种是通过import java.util.ResourceBundle类的getBundle(String baseName)方法加载. 注意:一定要区分路径格式 实现代码如下: package com.ut

  • Java加载properties文件实现方式详解

    java加载properties文件的方式主要分为两大类:一种是通过import java.util.Properties类中的load(InputStream in)方法加载: 另一种是通过import java.util.ResourceBundle类的getBundle(String baseName)方法加载. 注意:一定要区分路径格式 实现代码如下: package com.util; import java.io.FileInputStream; import java.io.Fil

  • 在 Linux 中不使用 CD 命令进入目录/文件夹的方法

    众所周知,如果没有 cd 命令,我们无法 Linux 中切换目录.这个没错,但我们有一个名为 shopt 的 Linux 内置命令能帮助我们解决这个问题. shopt 是一个 shell 内置命令,用于设置和取消设置各种 bash shell 选项,由于它已安装,因此我们不需要再次安装它. 是的,我们可以在启用此选项后,可以不使用 cd 命令切换目录. 我们将在本文中向你展示如何操作.这是一个小的调整,但对于那些从 Windows 迁移到 Linux 的新手来说非常有用. 这对 Linux 管理

随机推荐