zoukankan      html  css  js  c++  java
  • Spring的PropertyPlaceholderConfigurer

    在项目中我们一般将配置信息(如数据库的配置信息)配置在一个properties文件中,如下:

    jdbcUrl=jdbc:mysql://localhost:3306/flowable?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&useSSL=false&serverTimezone=UTC
    userName=root
    userPassword=123456
    jdbcDriver=com.mysql.cj.jdbc.Driver

    接着在Spring的配置文件中读取,有两种方式:

    方式一:

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <!-- 对于读取一个配置文件采取的方案 -->
            <property name="location" value="classpath:config.properties"></property>
            <!-- 对于读取两个以上配置文件采取的处理方案 -->
            <!--
            <property name="locations"> 
                <list>
                    <value>classpath:config.properties</value>
                    <value>classpath:config2.properties</value>
                </list>
            </property>
            -->
        </bean>

    方式二:

    <!--采用这种方式简化配置文件-->
    <context:property-placeholder location="classpath:config.properties"/>

    我们知道,不论是使用PropertyPlaceholderConfigurer还是通过context:property-placeholder这种方式进行实现,都需要记住,Spring框架不仅仅会读取我们的配置文件中的键值对,而且还会读取Jvm 初始化的一下系统的信息。有时候,我们需要将配置Key定一套命名规则 ,例如

    项目名称.组名.功能名=配置值
    org.team.tfunction=0001
    

    同时,我们也可以使用下面这种配置方式进行配置,这里我配NEVER的意思是不读取系统配置信息。如:

    <context:property-placeholder location="classpath:config.properties" system-properties-mode="NEVER"/>

    测试用例:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring-core.xml")
    public class SpringContextTest {
    
    	@Value("${userName}")
    	private String uname;
    
    	@Value("${userPassword}")
    	private String pwd;
    
    	@Test
    	public void test() {
    		System.out.println("username:" + uname);
    		System.out.println("password:" + pwd);
    	}
    
    }
    
    username:root
    password:123456

    配置文件中使用就比较简单了:

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
    		destroy-method="close">
    		<!-- 数据库基本信息配置 -->
    		<property name="url"
    			value="${jdbcUrl}" />
    		<property name="username" value="${userName}" />
    		<property name="password" value="${userPassword}" />
    		<property name="driverClassName" value="${jdbcDriver}" />
    </bean>
    
  • 相关阅读:
    python 基础2.5 循环中continue与breake用法
    python 基础 2.4 while 循环
    python 基础 2.3 for 循环
    python 基础 2.2 if流程控制(二)
    python 基础 2.1 if 流程控制(一)
    python 基础 1.6 python 帮助信息及数据类型间相互转换
    python 基础 1.5 python数据类型(四)--字典常用方法示例
    Tornado Web 框架
    LinkCode 第k个排列
    LeetCode 46. Permutations
  • 原文地址:https://www.cnblogs.com/foxting/p/8488441.html
Copyright © 2011-2022 走看看