您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
06-Spring配置数据源-Spring产生数据源对象(SpringConfig的bena产生数据源)
发布时间:2024-12-21 20:41:24编辑:雪饮阅读()
-
首先分享一个小技巧,在intelliJ IDEA中,如果你要拷贝一个class的完整路径含包名的那种,可以鼠标双击选中类名直接悬停在被拷贝类上面鼠标右键
Copy Reference
或Copy/Paste Special=>Copy Reference

然后就能得到如:com.mchange.v2.c3p0.ComboPooledDataSource
这样的完整类名
那么前番了解了通过bean进行注入,然后现在又了解了jdbc数据源的使用,现在可以结合注入bean注入的方式,利用Spring Config配置文件的方式进行获取数据源并获取jdbc连接。
核心原理就是数据源的相关set方法名后边部分名称首字母小写于property的name属性。
首先看看原本的一个获取数据源并打印jdbc的示例:
@Test
//测试c3p0数据源
public void testC3p0() throws Exception{
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://192.168.217.132/mybatis");
dataSource.setUser("root");
dataSource.setPassword("1448169a3cb137d7");
Connection connection=dataSource.getConnection();
System.out.println(connection);
connection.close();
}
那么接下来我们参考这个建立Spring Config配置文件于resources文件夹下如:
JDBCApplicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://192.168.217.132/mybatis"></property>
<property name="user" value="root"></property>
<property name="password" value="1448169a3cb137d7"></property>
</bean>
</beans>
那么我们的测试方法如:
@Test
//测试从bean中获取jdbc数据源并获取jdbc连接
public void testGetJDBCConnectFromBean() throws Exception{
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("JDBCApplicationContext.xml");
ComboPooledDataSource bean=app.getBean(ComboPooledDataSource.class);
Connection connection=bean.getConnection();
System.out.println(connection);
connection.close();
}
关键字词:Spring,Config,bean,数据源