Spring配置数据源
数据源(连接池)的作用
- 数据源(连接池)是提高程序性能而出现的
- 事先实例化数据源,初始化部分连接资源
- 使用连接资源时从数据源中获取
- 使用完毕后将连接资源归还给数据源
- 常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
数据源的开发步骤
- 导入数据源的坐标和数据库驱动坐标
- 创建数据源对象
- 设置数据源的基本连接数据
- 使用数据源获取连接资源和归还连接资源
数据源的手动创建
import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.sql.Connection;
import java.util.ResourceBundle;
public class DataSourceTest {
/*
* @Date: 2022/3/2 12:18
* 测试手动创建 c3p0 数据源
*/
@Test
public void test1() throws Exception {
//创建数据源dataSource
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置基本的连接参数:驱动、url、user、password
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai");
dataSource.setUser("root");
dataSource.setPassword("123456");
//通过dataSource获取连接资源
Connection connection = dataSource.getConnection();
System.out.println(connection);
//归还连接资源
connection.close();
}
/*
* @Date: 2022/3/2 12:39
* 测试手动创建 Druid 数据源
*/
@Test
public void test2() throws Exception {
//创建数据源dataSource
DruidDataSource dataSource = new DruidDataSource();
//设置基本的连接参数:驱动、url、user、password
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//通过dataSource获取连接资源
Connection connection = dataSource.getConnection();
System.out.println(connection);
//归还连接资源
connection.close();
}
/*
* @Date: 2022/3/2 12:46
* 测试手动创建 c3p0 数据源(加载properties配置文件)
*/
@Test
public void test3() throws Exception {
//读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String url = rb.getString("jdbc.url");
String username = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
//创建数据源对象,设置连接参数
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
}
}
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
Spring产生数据源对象
可以将DataSource的创建权交由Spring容器去完成
<!--以c3p0数据源为例-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息
首先,需要引入context命名空间和约束路径:
-
命名空间:
xlmns:context="http://www.springframework.org/schema/context"
-
约束路径:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!--加载外部的properties配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--通过${}从properties中获取jdbc参数信息-->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
Spring注解开发
Spring原始注解
-
Spring是轻代码、重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
-
Spring原始注解主要是替代<Bean>标签的配置
注解 | 说明 |
---|---|
@Component | 使用在类上,用于实例化Bean。后面三个的作用和他一样,只是可读性更强,能让我们知道这是哪一层 |
@Controller | 使用在Web层类上,用于实例化Bean |
@Service | 使用在Service层类上,用于实例化Bean |
@Repository | 使用在dao层类上,用于实例化Bean |
@Autowired | 使用在字段上,用于根据类型依赖注入 |
@Qualifier | 结合@Autowired一起使用,用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired + @Qualifier,按照名称进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
@PostConstruct | 使用在方法上,标注该方法是Bean的初始化方法 |
@PreDestroy | 使用在方法上,标注该方法是Bean的销毁方法 |
注意:
使用注解开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用功能注解配置的类、字段和方法。
<context:component-scan base-package="com.study"/>
package com.study.dao.impl;
import com.study.dao.UserDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
/**
* @title: UserDaoImpl
* @Author Mj
* @Date: 2022/3/2 14:09
* @Version 1.0
*/
//<bean id="userDao" class="com.study.dao.impl.UserDaoImpl"/>
// @Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("userDao save running...");
}
}
package com.study.service.impl;
import com.study.dao.UserDao;
import com.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
/**
* @title: UserServiceImpl
* @Author Mj
* @Date: 2022/3/2 14:12
* @Version 1.0
*/
//<bean id="userService" class="com.study.service.impl.UserServiceImpl"/>
// @Component("userService")
@Service("userService")
// @Scope("prototype")
public class UserServiceImpl implements UserService {
/*
* 如果只写@Autowired也是可以注入的
* 他是按照数据类型从spring容器中找到已经注入的UserDao类型的bean进行匹配后注入
*
* 如果spring容器中现在有多个相同类型的bean,则@Autowired不知道注入哪个
*
* @Qualifier("userDao")是根据id值从容器中进行匹配
* 但要注意的是,此处的@Qualifier要结合@Autowired一起使用
*
* @Resource(name = "userDao")相当于@Autowired + @Qualifier
* */
// <property name="userDao" ref="userDao"/>
/*@Autowired
@Qualifier("userDao")*/
@Resource(name = "userDao")
private UserDao userDao;
//注入普通属性
@Value("${jdbc.driver}")
private String driver;
/*
* 如果使用xml配置的方式注入,则需要set方法
* 使用注解方式,可以不要
* */
// public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
// }
public void save() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
public void init(){
System.out.println("Service对象初始化方法...");
}
@PreDestroy
public void destroy(){
System.out.println("Service对象销毁方法...");
}
}
package com.study.web;
import com.study.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @title: UserController
* @Author Mj
* @Date: 2022/3/2 14:14
* @Version 1.0
*/
public class UserController {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
((ClassPathXmlApplicationContext)app).close();
}
}
Spring新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
- 非自定义的Bean的配置:<bean>
- 加载properties文件的配置:<context:property-placeholder>
- 组件扫描的配置:<context:component-scan>
- 引入其他文件:<import>
注解 | 说明 |
---|---|
@Configuration | 用于指定当前类是一个Spring配置类,当创建容器时会从类上加载注解 |
@ComponentScan | 用于指定Spring在初始化容器时要扫描的包。作用和在Spring的xml配置文件中的<context:component-scan base-package=“com.study”/>一样 |
@Bean | 使用在方法上,标注将该方法的返回值存储到Spring容器中 |
@PropertySource | 用于加载.properties文件中的配置 |
@Import | 用于导入其他配置类 |
package com.study.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @title: DataSourceConfig
* @Author Mj
* @Date: 2022/3/2 17:33
* @Version 1.0
*/
/*
<!--加载外部的properties配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
*/
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource") //spring会将当前方法的返回值以指定名称存储到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
//创建数据源dataSource
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置基本的连接参数:驱动、url、user、password
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
package com.study.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @title: SpringConfiguration
* @Author Mj
* @Date: 2022/3/2 17:20
* @Version 1.0
*/
@Configuration //标识该类是Spring的核心配置文件
@Component //<context:component-scan base-package="com.study"/>
@Import({DataSourceConfig.class}) //加载DataSourceConfig这个分配置到SpringConfiguration这个核心配置中
public class SpringConfiguration {
}
package com.study.web;
import com.study.config.SpringConfiguration;
import com.study.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @title: UserController
* @Author Mj
* @Date: 2022/3/2 14:14
* @Version 1.0
*/
public class UserController {
public static void main(String[] args) {
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// AnnotationConfigApplicationContext()专门用来加载核心配置类
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService) app.getBean(UserService.class);
userService.save();
// ((ClassPathXmlApplicationContext)app).close();
}
}
Spring整合Junit
原始Junit测试Spring的问题
在测试类中,每个测试方法都有以下两行代码:
//获得容器上的对象
ApplicationContext app = new ClassPathXmlApplicationContext("bean.xml");
//获得要被测试的对象
IAccountService as = ac.getBean("accountService",IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
上述问题的解决思路
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉他
- 将需要进行测试Bean直接在测试类中进行注入,不需要再经过ApplicationContext
Spring集成Junit步骤
-
导入Spring集成Junit的坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.16</version> </dependency>
-
使用@RunWith(SpringJUnit4ClassRunner.class)注解替换原来的运行期
-
使用@ContextConfiguration指定配置文件或配置类
-
使用@Autowired注入需要测试的对象
-
创建测试方法进行测试
import com.study.config.SpringConfiguration;
import com.study.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* @title: SpringJunitTest
* @Author Mj
* @Date: 2022/3/2 20:57
* @Version 1.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
//配置文件方式
// @ContextConfiguration("classpath:applicationContext.xml")
//全注解方式
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println("SpringJunitTest test1 running..."+dataSource.getConnection());
}
}