一、Spring介绍
1.1 Spring简介
Spring是一个开源框架,为简化企业级开发而生。它以IOC(控制反转)和AOP(面向切面)为思想内核,提供了控制层SpringMVC、数据层SpringData、服务层事务管理等众多技术,并可以整合众多第三方框架。
Spring将很多复杂的代码变得优雅简洁,有效的降低代码的耦合度,极大的方便项目的后期维护、升级和扩展。
Spring官网地址:Spring | Home
1.2 Spring体系结构
Spring框架根据不同的功能被划分成了多个模块,这些模块可以满足一切企业级应用开发的需求,在开发过程中可以根据需求有选择性地使用所需要的模块。
- Core Container:Spring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。
- Data Access/Integration:该模块提供了数据持久化的相应功能。
- Web:该模块提供了web开发的相应功能。
- AOP:提供了面向切面编程实现
- Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。
- Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用。
- Messaging:为Spring框架集成一些基础的报文传送应用
- Test:提供与测试框架的集成
二、Spring IOC
2.1 控制反转思想
IOC(Inversion of Control) :程序将创建对象的权利交给框架。
之前在开发过程中,对象实例的创建是由调用者管理的,代码如下:
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"张三","北京");
}
}
public class StudentService {
public Student findStudentById(int id){
// 此处就是调用者在创建对象
StudentDao studentDao = new StudentDaoImpl();
return studentDao.findById(1);
}
}
这种写法有两个缺点:
-
浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象。
-
代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码。
而IOC思想是将创建对象的权利交给框架,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权发生了反转,这就是Spring的IOC思想。而IOC思想可以完美的解决以上两个问题。
2.2 Spring实现IOC
接下来我们使用Spring实现IOC,Spring内部也有一个容器用来管理对象。
1、创建Maven工程,引入依赖
<dependencies>
<!--spring核心依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
2、创建POJO类、dao层接口和实现类
public class Student {
private int id;
private String name;
private String address;
// 省略getter/setter/构造方法/tostring
}
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"张三","南京市");
}
}
3、在resources编写xml配置文件bean.xml ,配置文件中配置需要Spring帮我们创建的对象。
<?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">
<!--spring会读取该配置文件的信息将对象加载到spring容器中,注意class一定是接口的实现类。-->
<bean id="studentDao" class="com.zj.dao.StudentDaoImpl"></bean>
</beans>
4、测试
@Test
public void test1(){
//创建spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//从容器获取对象
StudentDao studentDao1 = (StudentDao) context.getBean("studentDao");
StudentDao studentDao2 = (StudentDao) context.getBean("studentDao");
System.out.println(studentDao1.hashCode());
System.out.println(studentDao2.hashCode());
System.out.println(studentDao1.findById(1));
}
hashcode值相同说明spring容器中只存在一个StudentDao的实例。
2.3 Spring容器类型
容器接口
-
BeanFactory:BeanFactory是Spring容器中的顶层接口,它可以对Bean对象进行管理。
-
ApplicationContext:ApplicationContext是BeanFactory的子接口。它除了继承 BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等方面的良好支持。
ApplicationContext有以下三个常用实现类:
容器实现类
ClassPathXmlApplicationContext:该类可以从项目中读取配置文件
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
FileSystemXmlApplicationContext:该类从磁盘中读取配置文件
ApplicationContext context = new FileSystemXmlApplicationContext("D:\\Java\\code\\learnSpringIOC\\src\\main\\resources\\bean.xml");
AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解
2.4 对象的创建方式
Spring会帮助我们创建bean,那么它底层是调用什么方法进行创建的呢?
使用构造方法
Spring默认通过反射机制使用类的空参构造方法创建bean,但是一般类会默认存在一个空参构造,只要自定义一个有参构造,那么无参构造就不会生效:
// 假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements StudentDao{
public StudentDaoImpl(int a){}
@Override
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"张三","北京");
}
}
使用工厂类的方法
除了使用空参构造创建对象之外,Spring还可以调用工厂类的方法创建bean:
1、创建工厂类,工厂类提供创建对象的方法
public class StudentDaoFactory {
public StudentDao getStudentDao(){
return new StudentDaoImpl(1);
}
}
2、在配置文件中配置创建bean的方式为工厂方式。
<!-- id:工厂对象的id,class:工厂类 -->
<bean id="studentDaoFactory" class="com.zj.dao.StudentDaoFactory"></bean>
<!-- id:bean对象的id,factory-bean:工厂对象的id,factory-method:工厂方法 -->
<bean id="studentDao" factory-bean="studentDaoFactory" factory-method="getStudentDao"></bean>
3、测试
@Test
public void test2() {
//创建spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
StudentDao studentDao = (StudentDao) context.getBean("studentDao");
Student student = studentDao.findById(1);
System.out.println(student);
}
使用工厂类的静态方法
Spring可以调用工厂类的静态方法创建bean:
1、创建工厂类,工厂提供创建对象的静态方法。
public class StudentDaoFactory2 {
public static StudentDao getStudentDao2() {
return new StudentDaoImpl();
}
}
2、在配置文件中配置创建bean的方式为工厂静态方法。
<!--静态方法的调用不需要创建对象-->
<!-- id:bean的id class:工厂全类名 factory-method:工厂静态方法 -->
<bean id="studentDao" class="com.zj.factory.StudentDaoFactory2" factory-method="getStudentDao2"></bean>
2.5 对象的创建策略
Spring通过配置<bean>
中的scope
属性设置对象的创建策略,共有五种创建策略:
1、singleton:单例,默认策略。整个项目只会创建一个对象,通过<bean>
中的lazy-init
属性可以设置单例对象的创建时机:
lazy-init="false"(默认):立即创建,在容器启动时会创建配置文件中的所有Bean对象。
lazy-init="true":延迟创建,第一次使用Bean对象时才会创建。
配置单例策略:
<?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="studentDao" class="com.zj.dao.StudentDaoImpl"/>
</beans>
测试单例策略:
public class StudentDaoImpl implements StudentDao {
public StudentDaoImpl() {
System.out.println("StudentDaoImpl对象创建了");
}
}
public class TestSpringContainer {
@Test
public void test1(){
//创建spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
}
}
2、prototype:多例,每次从容器中获取时都会创建对象。
<!-- 配置多例策略 -->
<bean id="studentDao" class="com.zj.dao.StudentDaoImpl" scope="prototype"></bean>
3、request:每次请求创建一个对象,只在web环境有效。
4、session:每次会话创建一个对象,只在web环境有效。
5、gloabal-session:一次集群环境的会话创建一个对象,只在web环境有效。
2.6 对象的销毁时机
对象的创建策略不同,销毁时机也不同:
- singleton:对象随着容器的销毁而销毁。
- prototype:使用JAVA垃圾回收机制销毁对象。
- request:当处理请求结束,bean实例将被销毁。
- session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
- gloabal-session:集群环境下的session销毁,bean实例也将被销毁。
2.7 生命周期方法
Bean对象的生命周期包含创建——使用——销毁,Spring可以配置Bean对象在创建和销毁时自动执行的方法:
1、定义生命周期方法
package com.zj.dao;
public class StudentDaoImpl implements StudentDao {
// 创建时自动执行的方法
public void init(){
System.out.println("创建StudentDaoImpl!!!");
}
// 销毁时自动执行的方法
public void destroy(){
System.out.println("销毁StudentDaoImpl!!!");
}
}
2、配置生命周期方法
<?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">
<!-- init-method:创建对象时执行的方法 destroy-method:销毁对象时执行的方法 -->
<bean id="studentDao" class="com.zj.dao.StudentDaoImpl" scope="singleton"
init-method="init" destroy-method="destroy"></bean>
</beans>
3、测试
package com.zj.dao;
import com.zj.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringContainer {
@Test
public void test1(){
//创建spring容器,单例模式下默认启动容器时创建对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//销毁Spring容器,ClassPathXmlApplicationContext才有销毁容器的方法
context.close();
}
}
2.8 获取Bean对象的方式
Spring有多种获取容器中对象的方式:
通过id/name获取
- 配置文件
<bean name="studentDao" class="com.zj.dao.StudentDaoImpl"/>
2、 获取对象
StudentDao studentDao = (StudentDao) context.getBean("studentDao");
通过类型获取
1、配置文件
<bean name="studentDao" class="com.zj.dao.StudentDaoImpl"/>
2、获取对象
StudentDaoImpl bean = context.getBean(StudentDaoImpl.class);
可以看到使用类型获取不需要强转。但是如果一个接口存在多个实现类的话不能使用该方式获取对象。因为spring容器不知道要获取哪个对象的实现类。
通过类型+id/name获取
虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型+id/name获取
1、配置文件
<bean name="studentDaoImpl1" class="com.zj.dao.StudentDaoImpl"></bean>
<bean name="studentDaoImpl2" class="com.zj.dao.StudentDaoImpl2"></bean>
2、获取对象
StudentDaoImpl studentDaoImpl1 = context.getBean("studentDaoImpl1", StudentDaoImpl.class);
StudentDaoImpl2 studentDaoImpl2 = context.getBean("studentDaoImpl2", StudentDaoImpl2.class);
三、Spring DI
3.1 什么是依赖注入
依赖注入(Dependency Injection,简称DI),它是Spring控制反转思想的具体实现。
控制反转将对象的创建交给了Spring,但是对象中可能会依赖其他对象。比如service类中要有dao类的属性,我们称service依赖于dao。之前需要手动注入属性值,代码如下:
public interface StudentDao {
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟根据id查询学生
return new Student(1,"张三","北京");
}
}
public class StudentService {
// service依赖dao,手动注入属性值,即手动维护依赖关系
private StudentDao studentDao = new StudentDaoImpl();
public Student findStudentById(int id){
return studentDao.findById(id);
}
}
此时,当StudentService的想要使用StudentDao的另一个实现类如StudentDaoImpl2时,则需要修改Java源码,造成代码的可维护性降低。
而使用Spring框架后,Spring管理Service对象与Dao对象,此时它能够为Service对象注入依赖的Dao属性值。这就是Spring的依赖注入。简单来说,控制反转是创建对象,依赖注入是为对象的属性赋值。
3.2 依赖注入方式
Setter注入
在之前开发中,可以通过setter方法或构造方法设置对象属性值:
// setter方法设置属性
StudentService studentService = new StudentService();
StudentDao studentDao = new StudentDao();
studentService.setStudentDao(studentDao);
// 构造方法设置属性
StudentDao studentDao = new StudentDao();
StudentService studentService = new StudentService(studentDao);
Spring可以通过调用setter方法或构造方法给属性赋值:
1、被注入类编写属性的setter方法
public class StudentService {
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
2、配置文件中,给需要注入属性值的<bean>
中设置<property>
<?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="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentService" class="com.zj.service.StudentServiceImpl">
<!--依赖注入。name:属性名,ref:bean的id-->
<property name="studentDao" ref="studentDaoImpl"/>
</bean>
</beans>
3、测试是否注入成功
StudentServiceImpl studentService = context.getBean("studentService", StudentServiceImpl.class);
StudentDao studentDao = studentService.getStudentDao();
构造方法依赖注入
1、被注入类编写有参的构造方法
package com.zj.service;
import com.zj.dao.StudentDao;
public class StudentServiceImpl implements StudentService {
private StudentDao studentDao;
public StudentServiceImpl(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
2、给需要注入属性值的<bean>
中设置<constructor-arg>
<bean id="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentService" class="com.zj.service.StudentServiceImpl">
<!--构造方法实现依赖注入-->
<constructor-arg name="studentDao" ref="studentDaoImpl"/>
</bean>
自动注入
自动注入不需要在<bean>
标签中添加其他标签注入属性值,而是自动从容器中找到相应的bean对象设置为属性值。
自动注入有两种配置方式:
- 全局配置:在
<beans>
中设置default-autowire
属性可以定义所有bean对象的自动注入策略。一般很少用了解即可。 - 局部配置:在
<bean>
中设置autowire
属性可以定义当前bean对象的自动注入策略。
autowire的取值如下:
- no:不会进行自动注入。
- default:全局配置default相当于no,局部配置default表示使用全局配置
- byName:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供set方法。
- byType:在Spring容器中查找类型与属性类型相同的bean,并进行注入。需要提供set方法。
- constructor:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供构造方法。
byType
1、为依赖的对象创建set/get方法
package com.zj.service;
import com.zj.dao.StudentDao;
import com.zj.dao.StudentDaoImpl;
public class StudentServiceImpl implements StudentService {
/*成员变量*/
private StudentDao studentDao;
/*set*/
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
/*get*/
public StudentDao getStudentDao() {
return studentDao;
}
/*带参构造方法*/
public StudentServiceImpl(int a){
}
}
2、在配置文件中配置根据类型自动注入
<!-- 根据bean类型等于属性类型自动注入 -->
<bean id="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentServiceImpl" class="com.zj.service.StudentServiceImpl" autowire="byType"/>
3、测试
@Test
public void test1(){
//创建spring容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//获取StudentServiceImpl
StudentServiceImpl studentServiceImpl = context.getBean("studentServiceImpl", StudentServiceImpl.class);
//获取studentServiceImpl中的StudentDaoImpl属性
StudentDao studentDao = studentServiceImpl.getStudentDao();
//调用StudentDaoImpl中的方法
studentDao.m1();
}
byName
<!-- 根据bean名称等于属性类型自动注入 -->
<bean id="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentServiceImpl" class="com.zj.service.StudentServiceImpl" autowire="byName"/>
constructor
<!-- 利用构造方法自动注入-->
<bean id="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentServiceImpl" class="com.zj.service.StudentServiceImpl" autowire="constructor"/>
注入bean、基本数据类型、字符串
1、准备注入属性的类
public class StudentService {
private StudentDao studentDao; // bean属性
private String name; //字符串类型
private int count; //基本数据类型
private List<String> names; // 字符串类型List集合
private List<Student> students1; // 对象类型List集合
private Set<Student> students2; // 对象类型Set集合
private Map<String,String> names2; // 字符串类型Map集合
private Map<String,Student> students3; // 对象类型Map集合
private Properties properties; //Properties类型
// 省略getter/setter/toString
}
2、注入bean类型、基本数据类型
<?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="studentDaoImpl" class="com.zj.dao.StudentDaoImpl"/>
<bean id="studentServiceImpl" class="com.zj.service.StudentServiceImpl">
<!--注入bean类型的数据-->
<property name="studentDao" ref="studentDaoImpl"/>
<!--注入基本数据类型-->
<property name="count" value="10"/>
<!--注入字符串类型的数据-->
<property name="name" value="张三"/>
<!--注入简单类型(String、Integer……)的list集合-->
<property name="names">
<list>
<value>李四</value>
<value>王五</value>
</list>
</property>
<!--注入对象类型的list集合-->
<property name="students1">
<list>
<bean class="com.zj.pojo.Student">
<property name="id" value="1"/>
<property name="name" value="苏问夏"/>
<property name="address" value="甘肃"/>
</bean>
<bean class="com.zj.pojo.Student">
<property name="id" value="2"/>
<property name="name" value="苍映天"/>
<property name="address" value="新疆"/>
</bean>
</list>
</property>
<!--注入对象类型的对象类型-->
<property name="students2">
<set>
<bean class="com.zj.pojo.Student">
<property name="id" value="1"/>
<property name="name" value="郜梓童"/>
<property name="address" value="杭州"/>
</bean>
<bean class="com.zj.pojo.Student">
<property name="id" value="2"/>
<property name="name" value="董孟阳"/>
<property name="address" value="福州"/>
</bean>
</set>
</property>
<!--注入简单类型的Map-->
<property name="names2">
<map>
<entry key="1" value="张姣姣"/>
<entry key="2" value="林韶仪"/>
</map>
</property>
<!--注入对象类型的map-->
<property name="students3">
<map>
<entry key="1" value-ref="student1"/>
<entry key="2" value-ref="student2"/>
</map>
</property>
<!--注入properties类型的对象-->
<property name="properties">
<props>
<prop key="配置1">值1</prop>
<prop key="配置2">值2</prop>
</props>
</property>
</bean>
<bean id="student1" class="com.zj.pojo.Student">
<property name="id" value="1"/>
<property name="name" value="段宵月"/>
<property name="address" value="廊坊"/>
</bean>
<bean id="student2" class="com.zj.pojo.Student">
<property name="id" value="2"/>
<property name="name" value="富好慕"/>
<property name="address" value="邢台"/>
</bean>
</beans>
3、测试
@Test
public void test1(){
//创建spring容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//获取StudentServiceImpl
StudentServiceImpl studentServiceImpl = context.getBean("studentServiceImpl", StudentServiceImpl.class);
//获取studentServiceImpl中的StudentDaoImpl属性
StudentDao studentDao = studentServiceImpl.getStudentDao();
//调用StudentDaoImpl中的方法
studentDao.m1();
System.out.println(studentServiceImpl);
}
StudentDaoImpl!!!
StudentService{studentDao=com.zj.dao.StudentDaoImpl@15bfd87, name='张三', count=10, names=[李四, 王五], students1=[Student{id=1, name='苏问夏', address='甘肃'}, Student{id=2, name='苍映天', address='新疆'}], students2=[Student{id=1, name='郜梓童', address='杭州'}, Student{id=2, name='董孟阳', address='福州'}], names2={1=张姣姣, 2=林韶仪}, students3={1=Student{id=1, name='段宵月', address='廊坊'}, 2=Student{id=2, name='富好慕', address='邢台'}}, properties={配置2=值2, 配置1=值1}}
四、注解实现IOC
4.1 准备工作
1、创建一个新的maven项目。
2、编写pojo,dao,service类。
3、编写空的配置文件,如果想让该文件支持注解,需要添加新的约束:
<?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">
</beans>
4.2 @Component
作用:用于创建对象,放入Spring容器,相当于<bean id="" class="">
位置:类上方
注意:
- 要在配置文件中配置扫描的包,扫描到该注解才能生效。
<context:component-scan base-package="com.zj"/>
@Component
注解配置bean的默认id是首字母小写的类名。也可以手动设置bean的id值。// 此时bean的id为studentDaoImpl @Component public class StudentDaoImpl implements StudentDao { public void m1(){ System.out.println("StudentDaoImpl!!!"); } } // 此时bean的id为studentDao @Component("studentDao") public class StudentDaoImpl implements StudentDao{ public void m1(){ System.out.println("StudentDaoImpl!!!"); } }
4.3 @Repository、@Service、@Controller、@Scope
作用:这三个注解和@Component的作用一样,使用它们是为了区分该类属于什么层。
位置:
- @Repository用于Dao层
- @Service用于Service层
- @Controller用于Controller层
@Repository
public class StudentDaoImpl implements StudentDao{}
@Service
public class StudentService {}
- @Scope
作用:指定bean的创建策略
位置:类上方
取值:singleton prototype request session globalsession
@Service
@Scope("singleton")
public class StudentService {}
4.4 @Autowired
作用:从容器中查找符合属性类型的对象自动注入属性中。用于代替<bean>
中的依赖注入配置。
位置:属性上方、setter方法上方、构造方法上方。
注意:
1、@Autowired
写在属性上方进行依赖注入时,可以省略setter方法
@Service
@Scope("singleton")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
public StudentDao getStudentDao() {
return studentDao;
}
public void m1(){
studentDao.m1();
}
}
2、容器中没有对应类型的对象会报错
3、容器中有多个对象匹配类型时,会找beanId等于属性名的对象,找不到会报错。
4.5 @Qualifier
作用:在按照类型注入对象的基础上,再按照bean的id注入。
位置:属性上方
注意:@Qualifier必须和@Autowired一起使用。
@Component
public class StudentService {
@Autowired
@Qualifier("studentDaoImpl2")
private StudentDao studentDao;
public Student findStudentById(int id){
return studentDao.findById(id);
}
}
4.6 @Value
作用:注入String类型和基本数据类型的属性值。
位置:属性上方
用法:
1、直接设置固定的属性值
@Service
public class StudentService {
@Value("1")
private int count;
@Value("hello")
private String str;
}
2、获取配置文件中的属性值:
- 编写配置文件db.properties
jdbc.username=root
jdbc.password=123456
- spring核心配置文件扫描配置文件
<context:property-placeholder location="db.properties"/>
- 注入配置文件中的属性值
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
4.7 @Configuration、@ComponentScan
此时基于注解的IOC配置已经完成,但是我们依然离不开Spring的xml配置文件。接下来我们脱离bean.xml,使用纯注解实现IOC。
在真实开发中,我们一般还是会保留xml配置文件,很多情况下使用配置文件更加方便。
注解实现IOC需要一个Java类代替xml文件。这个Java类上方需要添加@Configuration,表示该类是一个配置类,作用是代替配置文件。
@Configuration /*表示该类是一个配置类*/
@ComponentScan("com.zj") /*扫描包*/
public class SpringConfig {
}
@Test
public void test1(){
//创建spring容器
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//获取容器中的对象
StudentServiceImpl studentServiceImpl = context.getBean("studentServiceImpl", StudentServiceImpl.class);
StudentDao studentDao = studentServiceImpl.getStudentDao();
studentDao.m1();
}
4.8 @PropertySource
作用:代替配置文件中的<context:property-placeholder>
扫描配置文件
位置:配置类上方
注意:配置文件位置前要加关键字classpath
@Configuration
@PropertySource("classpath:db.properties")
public class JdbcConfig {
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
}
4.9 @Bean
作用:将方法的返回值对象放入Spring容器中。如果想将第三方类的对象放入容器,可以使用@Bean
位置:配置类的方法上方。
属性:name:给bean对象设置id
注意:@Bean修饰的方法如果有参数,spring会根据参数类型从容器中查找可用对象。
举例:如果想将jdbc连接对象放入Spring容器,我们无法修改Connection源码添加@Component,此时就需要使用将@Bean该对象放入Spring容器
1、添加驱动依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
2、将Connection对象放入Spring容器
@Bean(name = "connection")
public Connection getConnection(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql:///mybatis", "root", "123456");
} catch (Exception exception) {
return null;
}
}
3、测试
@Test
public void test1(){
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
Connection connection = (Connection) ac.getBean("connection");
System.out.println(connection);
}
4.10 @Import
作用:如果配置过多,会有多个配置类,该注解可以为主配置类导入其他配置类
位置:主配置类上方
// Jdbc配置类
@Configuration
public class JdbcConfig {
@Bean(name = "connection")
public Connection getConnection(){
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql:///mybatis", "root", "123456");
} catch (Exception exception) {
return null;
}
}
}
// 主配置类
@Configuration
@ComponentScan("com.zj")
@Import(JdbcConfig.class)
public class SpringConfig {
}
五、Spring整合MyBatis
我们知道使用MyBatis时需要写大量创建SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession等对象的代码,而Spring的作用是帮助我们创建和管理对象,所以我们可以使用Spring整合MyBatis,简化MyBatis开发。
5.1 创建maven项目,引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springandmybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--JDBC驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<!-- MyBatis与Spring的整合包,该包可以让Spring创建MyBatis的对象 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--单元测试-->
<!-- junit,如果Spring5整合junit,则junit版本至少在4.12以上 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring整合测试模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.13</version>
</dependency>
</dependencies>
</project>
5.2 编写配置文件
1、编写数据库配置文件db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=123456
2、创建MyBatis配置文件SqlMapConfig.xml,数据源、扫描接口都交由Spring管理,不需要在MyBatis配置文件中设置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
3、创建Spring配置文件applicationContext.xml
<?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">
<!--扫描包-->
<context:component-scan base-package="com.zj"/>
<!--读取配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--创建Spring封装过的SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
</bean>
<!--创建Spring封装的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 该对象可以自动扫描持久层接口,并为接口创建代理对象 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描的接口包 -->
<property name="basePackage" value="com.zj.dao"/>
</bean>
</beans>
5.3 准备实体类
public class Student {
private int id;
private String name;
private String sex;
private String address;
// 省略构造方法/getter/setter/tostring
}
5.4 编写持久层接口
@Repository
public interface StudentDao {
// 查询所有学生
@Select("select * from student")
List<Student> findAll();
// 添加学生
@Insert("insert into student values(null,#{name},#{sex},#{address})")
void add(Student student);
}
5.5 编写service类
package com.zj.service;
import com.zj.dao.StudentDao;
import com.zj.pojo.Student;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
/*直接使用代理对象*/
@Autowired
private StudentDao studentDao;
@Override
public List<Student> findAllStudents() {
return studentDao.findAllStudents();
}
}
5.6 测试
import com.zj.pojo.Student;
import com.zj.service.StudentService;
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 java.util.List;
//junit使用spring的方式运行代码,即自动获取spring容器
@RunWith(SpringJUnit4ClassRunner.class)
//spring容器创建时读取的配置文件
@ContextConfiguration(locations = "classpath:applicationContext.xml")
//配置类的写法
//@ContextConfiguration(classes = config.class)
public class TestStudentService {
@Autowired
private StudentService studentService;
@Test
public void testFindAllStudent() {
List<Student> allStudents = studentService.findAllStudents();
for (Student student : allStudents) {
System.out.println(student);
}
}
}
六、SpringAOP
AOP的全称是Aspect Oriented Programming,即面向切面编程。是实现功能统一维护的一种技术,它将业务逻辑的各个部分进行隔离,使开发人员在编写业务逻辑时可以专心于核心业务,从而提高了开发效率。
- 作用:在不修改源码的基础上,对已有方法进行增强。
- 实现原理:动态代理技术。
- 优势:减少重复代码、提高开发效率、维护方便
- 应用场景:事务处理、日志管理、权限控制、异常处理等方面。
6.1 AOP相关术语
为了更好地理解AOP,就需要对AOP的相关术语有一些了解
名称 | 说明 |
---|---|
Joinpoint(连接点) | 指能被拦截到的点,在Spring中只有方法能被拦截。(spirng中所有方法都能被称为连接点) |
Pointcut(切点) | 指要对哪些连接点进行拦截,即被增强的方法。(只有真正被增强的方法才叫切点) |
Advice(通知) | 指拦截后要做的事情,即切点被拦截后执行的方法 。 |
Aspect(切面) | 切点+通知称为切面 |
Target(目标) | 被代理的对象 |
Proxy(代理) | 代理对象 |
Weaving(织入) | 生成代理对象的过程 |
6.2 AOP入门
AspectJ是一个基于Java语言的AOP框架,在Spring框架中建议使用AspectJ实现AOP。
接下来我们写一个AOP入门案例:dao层的每个方法结束后都可以打印一条日志:
1、引入依赖
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2、编写通知类
package com.zj.advice;
//通知类
public class MyAdviceAspect {
//后置通知
public void AfterReturningMethod(JoinPoint joinPoint){
System.out.println("切点方法名:"+joinPoint.getSignature().getName());
System.out.println("哪个类执行的该方法:"+joinPoint.getTarget());
System.out.println("打印日志……");
}
}
3、配置切面(将切点和通知匹配到一起形成切面)
<!--通知对象-->
<bean id="myAdviceAspect" class="com.zj.advice.MyAdviceAspect"/>
<!--配置AOP-->
<aop:config >
<!--配置切面(切点+通知)-->
<aop:aspect ref="myAdviceAspect">
<!--配置切点;execution表达式的意思是StudentDao类下的所有方法都会被拦截-->
<aop:pointcut id="myPoint" expression=" execution(* com.zj.dao.StudentDao.*(..)) "/>
<!--配置后置通知-->
<aop:after-returning method="AfterMethod" pointcut-ref="myPoint"/>
</aop:aspect>
</aop:config>
4、测试
6.3 通知类型
AOP有以下几种常用的通知类型:
通知类型 | 描述 |
---|---|
前置通知 | 在方法执行前添加功能 |
后置通知 | 在方法正常执行后添加功能 |
异常通知 | 在方法抛出异常后添加功能 |
最终通知 | 无论方法是否抛出异常,都会执行该通知 |
环绕通知 | 在方法执行前后添加功能 |
package com.zj.advice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
//通知类
public class MyAdviceAspect {
//后置通知
public void AfterReturningMethod(JoinPoint joinPoint){
System.out.println("切点方法名:"+joinPoint.getSignature().getName());
System.out.println("哪个类执行的该方法:"+joinPoint.getTarget());
System.out.println("打印日志……");
}
//前置通知
public void BeforeMethod(JoinPoint joinPoint){
System.out.println("前置通知……");
}
//异常通知
public void AfterThrowingMethod(Exception exception){
System.out.println("异常:"+exception.getMessage());
System.out.println("异常通知……");
}
//最终通知
public void AfterMethod(JoinPoint joinPoint){
System.out.println("最终通知……");
}
//环绕通知
public Object RoundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前……");
Object proceed = proceedingJoinPoint.proceed();//执行原方法
System.out.println("环绕后……");
return proceed;
}
}
<!--通知对象-->
<bean id="myAdviceAspect" class="com.zj.advice.MyAdviceAspect"/>
<!--配置AOP-->
<aop:config >
<!--配置切面(切点+通知)-->
<aop:aspect ref="myAdviceAspect">
<!--配置切点;execution表达式的意思是StudentDao类下的所有方法都会被拦截-->
<aop:pointcut id="myPoint" expression=" execution(* com.zj.dao.StudentDao.*(..)) "/>
<!--前置通知-->
<aop:before method="BeforeMethod" pointcut-ref="myPoint"/>
<!--配置后置通知-->
<aop:after-returning method="AfterReturningMethod" pointcut-ref="myPoint"/>
<!--异常通知-->
<aop:after-throwing method="AfterThrowingMethod" pointcut-ref="myPoint" throwing="exception"/>
<!--最终通知-->
<aop:after method="AfterMethod" pointcut-ref="myPoint"/>
<!--环绕通知-->
<aop:around method="RoundMethod" pointcut-ref="myPoint"/>
</aop:aspect>
</aop:config>
6.4 切点表达式
使用AspectJ需要使用切点表达式配置切点位置,写法如下:
-
标准写法:访问修饰符 返回值 包名.类名.方法名(参数列表)
-
访问修饰符可以省略。
-
返回值使用
*
代表任意类型。 -
包名使用
*
表示任意包,多级包结构要写多个*
,使用*..
表示任意包结构 -
类名和方法名都可以用
*
实现通配。 -
参数列表
- 基本数据类型直接写类型
- 引用类型写
包名.类名
*
表示匹配一个任意类型参数..
表示匹配任意类型任意个数的参数
-
全通配:
* *..*.*(..)
6.5 多切面配置
我们可以为切点配置多个通知,形成多切面,比如希望dao层的每个方法结束后都可以打印日志并发送邮件:
1、编写发送邮件的通知:
public class MyAspectJAdvice2 {
// 后置通知
public void myAfterReturning(JoinPoint joinPoint) {
System.out.println("发送邮件");
}
}
2、配置切面
<!-- 通知对象 -->
<bean id="myAspectJAdvice" class="com.itbaizhan.advice.MyAspectAdvice"></bean>
<bean id="myAspectJAdvice2" class="com.itbaizhan.advice.MyAspectAdvice2"></bean>
<!-- 配置AOP -->
<aop:config>
<!-- 配置切面 -->
<aop:aspect ref="myAspectJAdvice">
<!-- 配置切点 -->
<aop:pointcut id="myPointcut" expression="execution(* *..*.*(..))"/>
<!-- 后置通知 -->
<aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/>
</aop:aspect>
<aop:aspect ref="myAspectJAdvice2">
<aop:pointcut id="myPointcut2" expression="execution(* com.itbaizhan.dao.UserDao.*(..))"/>
<aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut2"/>
</aop:aspect>
</aop:config>
6.6 注解配置AOP
1、在applicationContext.xml文件中开启AOP注解支持
<aop:aspectj-autoproxy/>
2、在通知类上方加入注解@Aspect
3、在通知方法上方加入注解@Before/@AfterReturning/@AfterThrowing/@After/@Around
package com.zj.advice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class MyAdviceAspect {
//后置通知
@AfterReturning("execution(* com.zj.dao.StudentDao.*(..))")
public void AfterReturningMethod(JoinPoint joinPoint){
System.out.println("切点方法名:"+joinPoint.getSignature().getName());
System.out.println("哪个类执行的该方法:"+joinPoint.getTarget());
System.out.println("打印日志……");
}
//前置通知
@Before("execution(* com.zj.dao.StudentDao.*(..))")
public void BeforeMethod(JoinPoint joinPoint){
System.out.println("前置通知……");
}
//异常通知
@AfterThrowing(value = "execution(* com.zj.dao.StudentDao.*(..))",throwing = "exception")
public void AfterThrowingMethod(Exception exception){
System.out.println("异常:"+exception.getMessage());
System.out.println("异常通知……");
}
//最终通知
@After("execution(* com.zj.dao.StudentDao.*(..))")
public void AfterMethod(JoinPoint joinPoint){
System.out.println("最终通知……");
}
//环绕通知
@Around("execution(* com.zj.dao.StudentDao.*(..))")
public Object RoundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前……");
Object proceed = proceedingJoinPoint.proceed();//执行原方法
System.out.println("环绕后……");
return proceed;
}
}
或者直接将切点提出来
package com.zj.advice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class MyAdviceAspect {
//切点
@Pointcut("execution(* com.zj.dao.StudentDao.*(..))")
public void point(){
}
//后置通知
@AfterReturning("point()")
public void AfterReturningMethod(JoinPoint joinPoint){
System.out.println("切点方法名:"+joinPoint.getSignature().getName());
System.out.println("哪个类执行的该方法:"+joinPoint.getTarget());
System.out.println("打印日志……");
}
//前置通知
@Before("point()")
public void BeforeMethod(JoinPoint joinPoint){
System.out.println("前置通知……");
}
//异常通知
@AfterThrowing(value = "point()",throwing = "exception")
public void AfterThrowingMethod(Exception exception){
System.out.println("异常:"+exception.getMessage());
System.out.println("异常通知……");
}
//最终通知
@After("point()")
public void AfterMethod(JoinPoint joinPoint){
System.out.println("最终通知……");
}
//环绕通知
@Around("point()")
public Object RoundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前……");
Object proceed = proceedingJoinPoint.proceed();//执行原方法
System.out.println("环绕后……");
return proceed;
}
}
配置类如何代替xml中AOP注解支持?
在配置类上方添加@EnableAspectJAutoProxy即可
@Configuration @ComponentScan("com.zj") @EnableAspectJAutoProxy public class SpringConfig { }
七、Spring事务
事务:不可分割的原子操作。即一系列的操作要么同时成功,要么同时失败。
开发过程中,事务管理一般在service层,service层中可能会操作多次数据库,这些操作是不可分割的。否则当程序报错时,可能会造成数据异常。
如:张三给李四转账时,需要两次操作数据库:张三存款减少、李四存款增加。如果这两次数据库操作间出现异常,则会造成数据错误。
1、创建数据库
2、创建实体类
package com.zj.pojo;
public class User {
private int id;
private String username;
private String sex;
private String address;
private int account;
//get/set/构造省略
}
3、创建maven项目(spring+mybatis),引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springandmybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--JDBC驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<!--事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<!-- MyBatis与Spring的整合包,该包可以让Spring创建MyBatis的对象 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--AOP框架: AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- junit,如果Spring5整合junit,则junit版本至少在4.12以上 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring整合测试模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.13</version>
</dependency>
</dependencies>
</project>
4、dao、service层
@Repository
public interface UserDao {
//根据id查找用户
@Select("select * from user where id = #{id}")
User findUserById(int id);
//修改用户余额
@Update("update user set account = #{account} where id = #{id}")
void updateUser(User user);
}
@Service
public class UserService {
@Autowired
private UserDao userDao;
//转账业务
public void updateUser(int id1, int id2,int money){
/*转出人减少金额*/
User user1 = userDao.findUserById(id1);
System.out.println("未转账之前:"+user1.getUsername()+"有"+user1.getAccount()+"元。");
user1.setAccount(user1.getAccount() - money);
userDao.updateUser(user1);
/*转入人增加金额*/
User user2 = userDao.findUserById(id2);
System.out.println("未转账之前:"+user2.getUsername()+"有"+user2.getAccount()+"元。");
user2.setAccount(user2.getAccount() + money);
userDao.updateUser(user2);
User userById1 = userDao.findUserById(id1);
System.out.println("转账之后:"+userById1.getUsername()+"有"+userById1.getAccount()+"元。");
User userById2 = userDao.findUserById(id2);
System.out.println("转账之后:"+userById2.getUsername()+"有"+userById2.getAccount()+"元。");
}
}
5、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--扫描包-->
<context:component-scan base-package="com.zj"/>
<!--读取数据源配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--创建Spring封装过的SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
</bean>
<!--创建Spring封装的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 该对象可以自动扫描持久层接口,并为接口创建代理对象 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描的接口包 -->
<property name="basePackage" value="com.zj.dao"/>
</bean>
<!--开启AOP注解支持-->
<aop:aspectj-autoproxy/>
</beans>
6、测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestUserService {
@Autowired
private UserService userService;
@Test
public void testUpdateUser(){
userService.updateUser(5,6,500);
}
}
这么看来似乎是没啥大问题但是如果在转账的时候出现错误的话会怎么样呢?下面我们就来模拟转账业务出现错误看看转账业务是否还能正常进行。
@Service
public class UserService {
@Autowired
private UserDao userDao;
//转账业务
public void updateUser(int id1, int id2,int money){
/*转出人减少金额*/
User user1 = userDao.findUserById(id1);
System.out.println("未转账之前:"+user1.getUsername()+"有"+user1.getAccount()+"元。");
user1.setAccount(user1.getAccount() - money);
userDao.updateUser(user1);
//模拟错误
int a = 1/0;
/*转入人增加金额*/
User user2 = userDao.findUserById(id2);
System.out.println("未转账之前:"+user2.getUsername()+"有"+user2.getAccount()+"元。");
user2.setAccount(user2.getAccount() + money);
userDao.updateUser(user2);
User userById1 = userDao.findUserById(id1);
System.out.println("转账之后:"+userById1.getUsername()+"有"+userById1.getAccount()+"元。");
User userById2 = userDao.findUserById(id2);
System.out.println("转账之后:"+userById2.getUsername()+"有"+userById2.getAccount()+"元。");
}
}
测试后
发现翟玲娇把钱转给了张晓但是钱没有到张晓的手里,钱丢了。我们希望的是转账业务要么成功要么失败。所以要使用事务。
7.1 事务管理方案
在Spring框架中提供了两种事务管理方案:
- 编程式事务:通过编写代码实现事务管理。
- 声明式事务:基于AOP技术实现事务管理。
在Spring框架中,编程式事务管理很少使用,我们对声明式事务管理进行详细学习。
Spring的声明式事务管理在底层采用了AOP技术,其最大的优点在于无需通过编程的方式管理事务,只需要在配置文件中进行相关的规则声明,就可以将事务规则应用到业务逻辑中。
使用AOP技术为service方法添加如下通知:
7.2 事务管理器
Spring依赖事务管理器进行事务管理,事务管理器即一个通知类,我们为该通知类设置切点为service层方法即可完成事务自动管理。由于不同技术操作数据库,进行事务操作的方法不同。如:JDBC提交事务是connection.commit()
,MyBatis提交事务是sqlSession.commit()
,所以Spring提供了多个事务管理器。
事务管理器名称 | 作用 |
---|---|
org.springframework.jdbc.datasource.DataSourceTransactionManager | 针对JDBC技术提供的事务管理器。适用于JDBC和MyBatis。 |
org.springframework.orm.hibernate3.HibernateTransactionManager | 针对于Hibernate框架提供的事务管理器。适用于Hibernate框架。 |
org.springframework.orm.jpa.JpaTransactionManager | 针对于JPA技术提供的事务管理器。适用于JPA技术。 |
org.springframework.transaction.jta.JtaTransactionManager | 跨越了多个事务管理源。适用在两个或者是多个不同的数据源中实现事务控制。 |
我们使用MyBatis操作数据库,接下来使用DataSourceTransactionManager
进行事务管理。
1、引入依赖
<!-- 事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.13</version>
</dependency>
<!-- 事务底层 AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
2、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描包-->
<context:component-scan base-package="com.zj"/>
<!--读取数据源配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--创建Spring封装过的SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
</bean>
<!--创建Spring封装的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 该对象可以自动扫描持久层接口,并为接口创建代理对象 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描的接口包 -->
<property name="basePackage" value="com.zj.dao"/>
</bean>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--事务相关配置-->
<tx:advice id="txAdvice">
<!--暂时都用默认配置-->
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置切面(切点+通知)-->
<aop:config>
<!--切点-->
<aop:pointcut id="point" expression="execution(* com.zj.service.*(..))"/>
<!--通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
</aop:config>
</beans>
3、再次测试
账户 没变说明事务管理是成功的。
7.3 事务控制的API
Spring进行事务控制的功能是由三个接口提供的,这三个接口是Spring实现的,在开发中我们很少使用到,只需要了解他们的作用即可:
PlatformTransactionManager接口
PlatformTransactionManager是Spring提供的事务管理器接口,所有事务管理器都实现了该接口。该接口中提供了三个事务操作方法:
- TransactionStatus getTransaction(TransactionDefinition definition):获取事务状态信息。
- void commit(TransactionStatus status):事务提交
- void rollback(TransactionStatus status):事务回滚
TransactionDefinition接口
TransactionDefinition是事务的定义信息对象,它有如下方法:
- String getName():获取事务对象名称。
- int getIsolationLevel():获取事务的隔离级别。
- int getPropagationBehavior():获取事务的传播行为。
- int getTimeout():获取事务的超时时间。
- boolean isReadOnly():获取事务是否只读。
TransactionStatus接口
TransactionStatus是事务的状态接口,它描述了某一时间点上事务的状态信息。它有如下方法:
- void flush() 刷新事务
- boolean hasSavepoint() 获取是否存在保存点
- boolean isCompleted() 获取事务是否完成
- boolean isNewTransaction() 获取是否是新事务
- boolean isRollbackOnly() 获取是否回滚
- void setRollbackOnly() 设置事务回滚
7.4 事务的相关配置
在<tx:advice>
中可以进行事务的相关配置:
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<tx:method>
中的属性:
- name:指定配置的方法。
*
表示所有方法,find*
表示所有以find开头的方法。- read-only:是否是只读事务,只读事务不存在数据的修改,数据库将会为只读事务提供一些优化手段,会对性能有一定提升,建议在查询中开启只读事务。
- timeout:指定超时时间,在限定的时间内不能完成所有操作就会抛异常。默认永不超时
- rollback-for:指定某个异常事务回滚,其他异常不回滚。默认所有异常回滚。
- no-rollback-for:指定某个异常不回滚,其他异常回滚。默认所有异常回滚。
- propagation:事务的传播行为
- isolation:事务的隔离级别
7.5 事务的传播行为
事务传播行为是指多个含有事务的方法相互调用时,事务如何在这些方法间传播。
如果在service层的方法中调用了其他的service方法,假设每次执行service方法都要开启事务,此时就无法保证外层方法和内层方法处于同一个事务当中。
// method1的所有方法在同一个事务中
public void method1(){
// 此时会开启一个新事务,这就无法保证method1()中所有的代码是在同一个事务中
method2();
System.out.println("method1");
}
public void method2(){
System.out.println("method2");
}
事务的传播特性就是解决这个问题的,Spring帮助我们将外层方法和内层方法放入同一事务中。
传播行为 | 介绍 |
---|---|
REQUIRED | 默认。支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。 |
SUPPORTS | 支持当前事务,如果当前没有事务,就以非事务方式执行。 |
MANDATORY | 支持当前事务,如果当前没有事务,就抛出异常。 |
REQUIRES_NEW | 新建事务,如果当前存在事务,把当前事务挂起。 |
NOT_SUPPORTED | 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 |
NEVER | 以非事务方式执行,如果当前存在事务,则抛出异常。 |
NESTED | 必须在事务状态下执行,如果没有事务则新建事务,如果当前有事务则创建一个嵌套事务 |
7.6 事务的隔离级别
事务隔离级别反映事务提交并发访问时的处理态度,隔离级别越高,数据出问题的可能性越低,但效率也会越低。
隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
READ_UNCOMMITTED(读取未提交内容) | Yes | Yes | Yes |
READ_COMMITTED(读取提交内容) | No | Yes | Yes |
REPEATABLE_READ(重复读) | No | No | Yes |
SERIALIZABLE(可串行化) | No | No | No |
如果设置为DEFAULT会使用数据库的隔离级别。
- SqlServer , Oracle默认的事务隔离级别是READ_COMMITTED
- Mysql的默认隔离级别是REPEATABLE_READ
7.7 注解配置声明式事务
Spring支持使用注解配置声明式事务。用法如下:
1、注册事务注解驱动
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--注册事务注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
2、在需要事务支持的方法或类上加@Transactional
@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class UserService {}
配置类代替xml中的注解事务支持:在配置类上方写@EnableTranscationManagement
@Configuration
@ComponentScan("com.zj")
@EnableTransactionManagement
public class SpringConfig {
@Bean
public DataSource getDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql:///mybatis");
druidDataSource.setUsername("root");
druidDataSource.setPassword("123456");
return druidDataSource;
}
@Bean
public SqlSessionFactoryBean getSqlSession(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer getMapperScanner(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.zj.dao");
return mapperScannerConfigurer;
}
@Bean
public DataSourceTransactionManager getTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}