Spring通过c3p0配置bean连接数据库

网友投稿 257 2022-12-30


Spring通过c3p0配置bean连接数据库

Spring配置bean连接数据库两种方法:

(1)直接在.xml文件内部配置:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.3.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.3.xsd">

(2)将参数放在外部文件中,然后再读入配置文件:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.3.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.3.xsd">

外部的配置文件:

user=root

password=wangjian

driverclass=com.mysql.jdbc.Driver

jdbcurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false

测试函数:

package com.primary.spring.beans.properties;

import java.sql.SQLExceptEAWoiVKwNfion;

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 {

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

DataSource dataSource = (DataSource) ctx.getBean("dataSource");

System.out.println(dataSource.getConnection());

}

}

测试结果:


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:嵌入式程序接口测试工具(嵌入式程序接口测试工具)
下一篇:物业管理系统接口设计方案(小区物业管理系统的设计)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~