Day16——引用外部属性文件配置C3P0连接池

一. 回顾

前面Day15——配置C3P0连接池讲到使用XML文件配置C3P0连接池。今天讲一下将XML文件里面的配置信息提取到外部文件中,再在XML文件里面引用那个外部文件去配置连接池。

本文章的项目源码已上传到本博客的“资源”处,可前往免费下载

二. 储备知识

当Bean的配置信息主键增多时,查找和修改一些bean的配置信息就变得愈加困难。==这时可以将一部分的配置信息提取到bean配置文件的外部,以properties格式的属性文件保存起来,同时在bean配置文件中引用properties属性文件中的内容。==从而实现一部分属性值发生变化时仅需修改properties属性文件即可。这种技术多用于连接数据库的基本信息的配置。

三. 例子

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/onlinebookshop
jdbc.user=root
jdbc.password=123456
jdbc.initPoolSize=5
jdbc.maxPoolSize=20

spring-dbProperties.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">

     <!-- 第一种引用方式 -->
   <!--  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location" value="classpath:db.properties"></property>
    </bean>  -->
    
     <!-- 第二种方式 -->
     <context:property-placeholder location="classpath:db.properties"/>
     
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
</beans>

Main.java

package com.atguigu.spring.dbProperties;


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 Exception {
		// TODO Auto-generated method stub
        ApplicationContext context = 
        		new ClassPathXmlApplicationContext("spring-dbProperties.xml");
        DataSource ds = context.getBean("dataSource", DataSource.class);
        System.out.println(ds);
        System.out.println(ds.getConnection());
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值