Spring管理数据源
Spring管理数据源
将数据源(dateSource)交给IOC容器进行管理,最终去实现Spring整合MyBatis
引入依赖
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
创建配置文件
在resources
目录下创建spring类型的配置文件spring-datasource.xml
,创建<bean>
spring-datasource.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">
<!--使用DataSource的实现类去管理数据源,这里使用的是DruidDataSource-->
<bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource">
<!--把连接数据库的信息配置好,需要配置类中的属性(依赖注入)-->
<!--这里的属性名为driverClassName,与MyBatis的driver有所不同-->
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="yuxingxuan"/>
<!--
可以配置和数据源相关的属性
initialSize:数据库连接池中初始化连接个数
maxActive:数据库连接池中最大能够连接的数量(默认为8)
maxWait:等待分配连接的最大等待时间(不设置为一直阻塞)
-->
</bean>
</beans>
DataSourceTest.java
@Test
public void testDataSource(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
DruidDataSource druidDataSource = ioc.getBean(DruidDataSource.class);
try {
System.out.println(druidDataSource.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
//输出结果:"地址"
引入外部属性
使用properties
文件,在resource
目录下创建properties
类型文件
jdbc.properties.xml
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username = root
jdbc.password = yuxingxuan
引入文件到spring-datasource.xml
<!--
引入jdbc.properties,通过${key}的方式访问value
1.<bean>的class属性PropertyPlaceholderConfigurer
2.<context>的property-placeholder约束
-->
<context:property-placeholder location="jdbc.properties"/>