Spring 学习(八)——使用外部属性文件

配置文件里配置 Bean , 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离

Spring 提供了一个 PropertyPlaceholderConfigurer BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件. 可以在 Bean 配置文件里使用形式为 ${var} 的变量, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.

Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。

注册 PropertyPlaceholderConfigurer

Spring 2.0:

Spring 2.5 之后: 可通过 <context:property-placeholder> 元素简化:

<beans> 中添加 context Schema 定义

在配置文件中加入如下配置

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

bean-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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
	   http://www.springframework.org/schema/context
	   http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--导入属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--使用外部化属性文件的属性-->
        <property name="driverClass" value="${driverClass}"/>
        <property name="jdbcUrl" value="${jdbcUrl}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>
</beans>

db.properties

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF8
user=root
password=root

Main.java

package com.hzyc.spring.bean.properties;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author xuehj2016
 * @Title: Main
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/1717:05
 */
public class Main {
    public static void main(String[] args) throws SQLException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-properties.xml");

        DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41577923/article/details/85059024