Spring 使用外部属性文件(连接数据库)

需要jar包:
c3p0-0.9.2.1.jar
mchange-commons-java-0.2.3.4.jar
mysql-connector-java-5.1.33-bin.jar

beans的配置文件:
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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="driverClass" value="${driverClass}" />
        <property name="jdbcUrl" value="${jdbcUrl}" />
        <property name="user" value="${user}" />
        <property name="password" value="${password}" />
    </bean>
</beans>

数据库属性文件db.properties(在src目录下):

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

Main.java

package com.haitun.bean;


import javax.sql.DataSource;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {

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

        //1.创建Spring IOC容器
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

        //连接数据库
        DataSource dataSources=(DataSource) context.getBean("datasource");
        System.out.println(dataSources.getConnection());
        context.close();
    }

}
展开阅读全文

没有更多推荐了,返回首页