`

spring 加载配置文件 xml 和properties

    博客分类:
  • SSIH
 
阅读更多
Spring配置文件是集成了Spring框架的项目的核心,引擎从哪里开始,中间都执行了哪些操作,小谈一下它的执行流程。

加载xml情况
容器先是加载web.xml

接着是applicationContext.xml在web.xml里的注册

一种方法是加入ContextLoaderServlet这个servlet

1 <context-param> 
2         <param-name>contextConfigLocation</param-name> 
3         <param-value>/WEB-INF/applicationContext.xml</param-value> 
4     </context-param> 
5      <servlet> 
6         <servlet-name>context</servlet-name> 
7         <servlet-class> 
8             org.springframework.web.context.ContextLoaderServlet  
9         </servlet-class> 
10         <load-on-startup>0</load-on-startup> 
11     </servlet> 
复制代码


还有一种是添加ContextLoaderListener这个监听器


1 <context-param> 
2     <param-name>contextConfigLocation</param-name> 
3     <param-value>/WEB-INF/applicationContext.xml</param-value> 
4 </context-param> 
5  
6 <listener> 
7     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
8 </listener> 



ContextLoaderServlet和ContextLoaderListener都是先创建ContextLoader的一个对象,然后调用它的initWebApplicationContex方法初始化WebApplicationContext获得一个对象;


spring加载多个配置文件,在web.xml中

1 <context-param>
2         <param-name>contextConfigLocation</param-name>
3         <param-value>classpath*:spring/*.xml</param-value>
4 </context-param>
5
6 <servlet>
7         <servlet-name>SpringContextServlet</servlet-name>
8         <servlet-class>
9             org.springframework.web.context.ContextLoaderServlet
10         </servlet-class>
11         <load-on-startup>3</load-on-startup>
12 </servlet>

加载Properties

一个系统中通常会存在如下一些以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 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: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中的值:
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-mvc.xml spring-mybatis.xml web.xml log4j.properties)

    spring-mvc.xml spring-mybatis.xml web.xml log4j.properties,项目中需要用到的配置文件。直接可用。

    Spring 自定义注解注入properties文件的值jar包

    在xml配置文件中,这样加载properties文件 &lt;bean id="propertyConfigurer" class="com.better517na.propertiesComponent.business.ExtendedPropertyPlaceholderConfigurer"&gt; &lt;value&gt;classpath:...

    SpringMVC+Mybatis JAVA配置 非XML

    2,加载properties配置文件 3,集成mybatis 4,配置事务 5,另一种配置springMVC的方式 6,自定义(扩展)mvc配置 7,解决@ResponseBody return String的中文乱码问题 8,配置静态资源映射ResourceHandlers 9,配置View...

    JAVA Spring框架实现登陆查询 完整搭建框架方法的word文档 包含mysql文件

    3 导入配置文件,将如下配置文件导入到src下面 3.1 修改generatorConfig.xml文件,这个是mybatis的逆向工程,修改数据库名,用户名,密码,对应的包名,对应的项目。如图 3.2 修改jdbc.properits文件, 3.3 log...

    Struts课堂笔记.rar--struts2的struts.properties配置文件详解

    struts自动加载的一个配置文件列表 struts.configuration.xml.reload Whether to reload the XML configuration or not 是否加载xml配置(true,false) struts.continuations.package The package containing ...

    SpringMVC+Mybatis+Maven 纯XML配置

    2,加载properties配置文件 3,集成mybatis 4,配置事务 5,另一种配置springMVC的方式 6,自定义(扩展)mvc配置 7,解决@ResponseBody return String的中文乱码问题 8,配置静态资源映射ResourceHandlers 9,配置View...

    从零开始学Spring Boot

    1.34 Spring Boot导入XML配置 1.35 Spring Boot使用@SpringBootApplication注解 1.36 Spring Boot 监控和管理生产环境 1.37 Spring Boot的启动器Starter详解 1.38 Spring Boot集成Redis实现缓存机制 1.39 Spring ...

    mina2.0+spring

    自己整理结合网上的诸多资料开发的一个中间件,当然这个是demo,想做成完整的通讯中间件的话需要在handler处做处理,并对加载配置文件处做修改方可导出成jar集成到其他系统。 这里简单说下: 1.ij.properties配置...

    Spring.net框架

    为此,我们引入“工厂”模式,并利用配置文件和反射技术,动态加载和装配相关组件。 三、基于配置文件和Reflection的工厂模式 为了消除MainApp对其它组件的依赖性,我们引入工厂模式,并且根据配置文件指定的装配...

    springboot框架集成说明

    引用mybatis jar包、创建使用的配置文件spring-application.xml、创建公共基础调用类baseDao对象、集成使用。Redis作为日常系统中一个重要的缓存库,在一些固定数据保存、短信验证码保存,以及一些系统交互及session...

    叮当书城项目-叮当书城项目部署代码视频教程带源码(java毕业设计项目-java练手项目)

    3、config文件,里面是我们的配置文件,jdbc.properties是对数据库连接的配置,mybatis-config.xml是对mapper.xml文件进行扫描的配置, spring.xml主要是配置组件扫描器,加载外部的properties配置文件,配置数据库...

    Java加载资源文件的两种方法

     当我们自己的程序需要处理配置文件时(比如xml文件或properties文件),通常会遇到两个问题:  (1)我的配置文件应该放在哪里?  (2)怎么我的配置文件找不到了?  在了解了Java加载资源文件的机制后...

    Spring中文帮助文档

    6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    Spring API

    6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...

    Myeclipse开发struts+hibernate+spring新手入门--环境配置---项目开发示例

    3、配置struts-config.xml文件;建立action、formbean; 改配置可以自动生成,使用eclipse进行自动生成,在建立时,如下图,可直接生成对应的action类和formbean类。 1 &lt;?xml version="1.0" encoding="UTF-8"?&gt; 2 ...

    configServer:Spring Cloud 配置服务器教程

    ###ConfigLocal 这个 µService 从本地文件系统加载它的配置。 这是最简单的情况,但违反了 12 因素,因为道具在本地捆绑在: /src/main/resources/application.yml这是一个 yml 文件,但我们也支持常规属性文件,...

    ssh(structs,spring,hibernate)框架中的上传下载

    WEB-INF下的applicationContext.xml为Spring的配置文件,struts-config.xml为Struts的配置文件,file-upload.jsp为文件上传页面,file-list.jsp为文件列表页面。  本文后面的章节将从数据持久层->业务层->Web层的...

    mybatis学习笔记

    3 SqlMapConfig.xml配置文件 24 3.1 配置内容 24 3.2 properties(属性) 24 3.3 settings(配置) 25 3.4 typeAliases(类型别名) 26 3.4.1 mybatis支持别名: 26 3.4.2 自定义别名: 27 3.5 typeHandlers(类型...

    spring3.2+strut2+hibernate4

    -- 当配置文件修改后,系统自动加载该文件。开发阶段建议打开此功能 --&gt; &lt;constant name="struts.counfiguraction.xml.reload" value="true"/&gt; &lt;!-- 指定浏览器输出的编码格式 --&gt; &lt;!--将action内容放在...

    Struts2属性文件详解

    该属性指定Struts 2框架默认加载的配置文件,如果需要指定默认加载多个配置文件,则多个配置文件的文件名之间以英文逗号(,)隔开.该属性的默认值为struts- default.xml,struts-plugin.xml,struts.xml,看到该属性值,所以...

Global site tag (gtag.js) - Google Analytics