spring_(8)使用外部属性文件

  • 在配置文件里配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源配置信息等).而这些部署细节实际上需要和Bean配置相分离.
  • Spring提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分外移到属性文件中.可以在Bean配置文件里使用形式为${var}的变量,PropertyPlaceholderConfigurer从属性文件里加载属性,并使用这些属性来替换变量.
  • Spring还允许在属性文件中使用${propName},以实现属性之间的相互作用.

概而论之:让配置文件 使用properties资源文件里面的数据库连接的资料,为以后的修改资料降低成本

例子程序

基本程序结构:

在这里插入图片描述

db.properties

user=root
password=****
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///freetalk

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: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.xsd">

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

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

    <!--
        之前的配置方法,若要修改,成本较高
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            &lt;!&ndash;使用外部化属性文件的属性&ndash;&gt;
            <property name="user" value="root"></property>
            <property name="password" value="etron"></property>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql:///freetalk"></property>
         </bean>
     -->


</beans>

Main.java

package com.spring.beans.properties;

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

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

public class Main {

    public static void main(String[] args) throws SQLException {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");

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

    }
}

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/84175895