Spring配置数据源
可以将DataSource的创建权交由Spring容器去完成
首先添加坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
之后创建spring配置文件 applicationContext.xml
添加bean
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
最后在 DataSourceTest类添加方法test4
@Test
//测试Spring 容器产生数据源对象
public void test4() throws Exception{
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过getBean获取dataSource
DataSource dataSource = app.getBean(DataSource.class);
//下面的和之前一样
Connection connection=dataSource.getConnection();
System.out.println(connection);
connection.close();
}