spring之使用外部属性文件(连接数据库时使用)

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

(2)spring提供了一个PropertyPlaceHolderConfigure的BeanFactory后置处理器。这个处理器允许用户将Bean配置文件的部分内容转移到属性文件中,可以在bean配置文件里使用形式为${var}的变量。PropertyPlaceHolderConfigre从属性文件里加载属性,并使用这些属性来替换变量。

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

将c3p0和mysql驱动加入到build path中。

首先确保启动了mysql服务,然后在配置文件中引入context命名空间。

db.properties

user=root
password=123456
jdbcUrl=jdbc:mysql:///test
driverClass=com.mysql.jdbc.Driver

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-4.3.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="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${driverClass}"></property>

    </bean>
    
</beans>

Main.java

package com.gong.spring.beans.properties;

import java.sql.SQLException;

import javax.sql.DataSource;

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

public class Main {
    public static void main(String[] args) throws SQLException {
        //1.创建spring的IOC容器对象
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");
        //2.从容器中获取Bean实例
        DataSource dataSource = (DataSource) ctx.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
}

当看到输出为:

则说明配置成功。 

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12152636.html
今日推荐