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
} 

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

在很多情况下我们需要在配置文件中配置一些属性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer类,可以方便我们使用注解直接注入properties文件中的配置。

下面我们看下具体如何操作:

首先要新建maven项目,并在pom文件中添加spring依赖,如下pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>cn.outofmemory</groupId>
 <artifactId>hellospring.properties.annotation</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>hellospring.properties.annotation</name>
 <url>http://maven.apache.org</url>
 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <org.springframework-version>3.0.0.RC2</org.springframework-version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <!-- Spring -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
  </dependency>
 </dependencies>
</project>

要自动注入properties文件中的配置,需要在spring配置文件中添加org.springframework.beans.factory.config.PropertiesFactoryBeanorg.springframework.beans.factory.config.PreferencesPlaceholderConfigurer的实例配置:

如下spring配置文件appContext.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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
  <!-- bean annotation driven -->
  <context:annotation-config />
  <context:component-scan base-package="cn.outofmemory.hellospring.properties.annotation">
  </context:component-scan>
  <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
      <list>
        <value>classpath*:application.properties</value>
      </list>
    </property>
  </bean>
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties" />
  </bean>
</beans>

在这个配置文件中我们配置了注解扫描,和configProperties实例和propertyConfigurer实例。这样我们就可以在java类中自动注入配置了,我们看下java类中如何做:

package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MySQLConnectionInfo {
  @Value("#{configProperties['mysql.url']}")
  private String url;
  @Value("#{configProperties['mysql.userName']}")
  private String userName;
  @Value("#{configProperties['mysql.password']}")
  private String password;
  /**
   * @return the url
   */
  public String getUrl() {
    return url;
  }
  /**
   * @return the userName
   */
  public String getUserName() {
    return userName;
  }
  /**
   * @return the password
   */
  public String getPassword() {
    return password;
  }
}

自动注入需要使用@Value注解,这个注解的格式#{configProperties['mysql.url']}其中configProperties是我们在appContext.xml中配置的beanId,mysql.url是在properties文件中的配置项。

properties文件的内容如下:

mysql.url=mysql's url
mysql.userName=mysqlUser
mysql.password=mysqlPassword

最后我们需要测试一下以上写法是否有问题,如下App.java文件内容:

package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Hello world!
 *
 */
public class App
{
  public static void main( String[] args )
  {
    ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
    MySQLConnectionInfo connInfo = appContext.getBean(MySQLConnectionInfo.class);
    System.out.println(connInfo.getUrl());
    System.out.println(connInfo.getUserName());
    System.out.println(connInfo.getPassword());
  }
}

在main方法中首先声明了appContext,然后获得了自动注入的MySQLConnectionInfo的实例,然后打印出来,运行程序会输出配置文件中配置的值

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

(0)

相关推荐

  • SpringBoot整个启动过程的分析

    前言 前一篇分析了SpringBoot如何启动以及内置web容器,这篇我们一起看一下SpringBoot的整个启动过程,废话不多说,正文开始. 正文 一.SpringBoot的启动类是**application,以注解@SpringBootApplication注明. @SpringBootApplication public class CmsApplication { public static void main(String[] args) { SpringApplication.run

  • Spring线程池ThreadPoolExecutor配置并且得到任务执行的结果

    用ThreadPoolExecutor的时候,又想知道被执行的任务的执行情况,这时就可以用FutureTask. ThreadPoolTask package com.paul.threadPool; import java.io.Serializable; import java.util.concurrent.Callable; public class ThreadPoolTask implements Callable<String>, Serializable { private s

  • Spring框架十一种常见异常的解决方法汇总

    在程序员生涯当中,提到最多的应该就是SSH三大框架了.作为第一大框架的Spring框架,我们经常使用. 然而在使用过程中,遇到过很多的常见异常,我在这里总结一下,大家共勉. 一.找不到配置文件的异常 org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/herman/ss/controller];

  • SpringBoot深入理解之内置web容器及配置的总结

    前言 在学会基本运用SpringBoot同时,想必搭过SSH.SSM等开发框架的小伙伴都有疑惑,SpringBoot在spring的基础上做了些什么,使得使用SpringBoot搭建开发框架能如此简单,便捷,快速.本系列文章记录网罗博客.分析源码.结合微薄经验后的总结,以便日后翻阅自省. 正文 使用SpringBoot时,首先引人注意的便是其启动方式,我们熟知的web项目都是需要部署到服务容器上,例如tomcat.weblogic.widefly(以前叫JBoss),然后启动web容器真正运行我

  • Spring Boot中使用Spring-data-jpa的配置方法详解

    为了解决这些大量枯燥的数据操作语句,我们第一个想到的是使用ORM框架,比如:hibernate.通过整合Hibernate之后,我们以操作Java实体的方式最终将数据改变映射到数据库表中. 为了解决抽象各个Java实体基本的"增删改查"操作,我们通常会以泛型的方式封装一个模板Dao来进行抽象简化,但是这样依然不是很方便,我们需要针对每个实体编写一个继承自泛型模板Dao的接口,再编写该接口的实现.虽然一些基础的数据访问已经可以得到很好的复用,但是在代码结构上针对每个实体都会有一堆Dao的

  • Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法

    先来看问题 纠结了几个小时终于找到了问题所在,因为shiro的realm属于Filter,简单说就是初始化realm时,spring还未加载相关业务Bean,那么解决办法就是将springmvc的配置文件加载提前. 解决办法 打开web.xml文件 OK,问题解决! 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持.如果你想了解更多相关内容请查看下面相关链接

  • SpringBoot集成shiro,MyRealm中无法@Autowired注入Service的问题

    网上说了很多诸如是Spring加载顺序,shiroFilter在Spring自动装配bean之前的问题,其实也有可能忽略如下低级错误. 在ShiroConfiguration中要使用@Bean在ApplicationContext注入MyRealm,不能直接new对象. 道理和Controller中调用Service一样,都要是SpringBean,不能自己new. 错误方式: @Bean(name = "securityManager") public SecurityManager

  • Spring集成jedis的配置与使用简单实例

    jedis是redis的java客户端,spring将redis连接池作为一个bean配置. redis连接池分为两种,一种是"redis.clients.jedis.ShardedJedisPool",这是基于hash算法的一种分布式集群redis客户端连接池. 另一种是"redis.clients.jedis.JedisPool",这是单机环境适用的redis连接池. maven导入相关包: <!-- redis依赖包 --> <depende

  • Spring各版本新特性的介绍

    Spring各个版本新特性 Spring3.1新特性 1.添加了引入环境profile功能 2.添加了@enable注解,使用特定功能 3.添加了对声明式缓存的支持,能够使用简单的注解声明缓存边界和规则 4.添加的用于构造器注入的c命名空间,类似与Spring2的p命名空间,用于对应属性注入 5.开始支持Servlet3.0,包括基于java配置中生命Servlet和Filter,不再只仅仅借助web.xml 6.改善对于JPA的支持,让JPA能在Spring中完整配置JPA,不必再使用pers

  • mysql+spring+mybatis实现数据库读写分离的代码配置

    场景:一个读数据源一个读写数据源. 原理:借助spring的[org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource]这个抽象类实现,看名字可以了解到是一个路由数据源的东西,这个类中有一个方法 /** * Determine the current lookup key. This will typically be * implemented to check a thread-bound transaction

随机推荐