1.Spring简介
1.1Spring概述
1、Spring 是轻量级的开源的 JavaEE 框架
2、Spring 可以解决企业应用开发的复杂性
3、Spring 有两个核心部分:IOC 和 Aop
(1)IOC:控制反转,把创建对象过程交给 Spring 进行管理
(2)Aop:面向切面,不修改源代码进行功能增强
4、Spring 特点
(1)方便解耦,简化开发
(2)Aop 编程支持
(3)方便程序测试
(4)方便和其他框架进行整合
(5)方便进行事务操作
(6)降低 API 开发难度
1.2Spring家族
项目列表:https://spring.io/projects
1.3Spring Framework
Spring基础框架,可以视为Spring基础设施,基本上任何其他spring项目都是以Spring Framework为基础的
1.3.1Spring Framework特性
•非侵入式:使用 Spring Framework 开发应用程序时,Spring 对应用程序本号的结构影啊非常小。对领域模型可以做到零污染;对功能性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这就使得基于 Spring Framework 开发应用程序时结构清晰、简洁优雅。
•控制反转:1OC一Inversion of Control,翻转资源获取方向。把目己创建资源、向环境获取资源变成环境将资源准备好,我们享受资源入注。
•自回功面编程:AOP–Aspect Oriented Programming, 在不修改源代码的基础上增强代码功能。
•容器:Spring lOC是一个容器,因为它包含并且管理组件对家的生命周期。组件享受到了容器化的管理,程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发双率。
•组件化:Spring 实现了使用简单的组件配置组合成一个复杂的应用。在Spring 中可以使用XML和Java注解组合这些对象。这使得我们可以基于一个个功能明确、 边界清晰的组件有条不絮的搭建超大型复杂应用系统
•声明式:很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
•一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且Spring旗下的项目已经覆盖了广泛的领域,很多方面的功能性需求可以在Spring Framework的基础上全部使用Spring来实现。
1.3.2Spring Framework五大功能模块
功能模块 | 功能介绍 |
---|---|
Core Container | 核心容器,在Spring环境下使用任何功能都必须基于IOC容器 |
AOP&Aspects | 面向切面编程 |
Testing | 提供了对junit或TestNG测试框架的整合 |
Data Access/Integration | 提供了对数据访问/集成的功能 |
Spring MVC | 提供了面向Web应用程序的集成功能 |
2.IOC
2.1 IOC容器
2.1.1 IOC思想
IOC:Inversion of Control,翻译过来死反转控制。
- 获取资源的传统方式
在应用程序中的组件需要获取资源时,传统的方式时组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同使降低了开发效率。 - 反转控制方式获取资源
反转的控制思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向–改变容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。 - DI
DI:Dependency Injection,翻译过来是依赖注入
DI是IOC的另一种表达方式:即组件以一些预先定义好的方式(例如:setter方法)接受来自容器的资源注入。相对宇IOC而言,这种表述更直接。
所以结论是:IOC就是一种反转控制的思想,而DI是对IOC的一种具体实现。
2.1.2IOC容器在Spring中的实现
Spring的IOC容器就是IOC实现的一个落地的产品实现。IOC容器中的管理的组件也叫做bean。在创建bean之前,首先需要创建IOC容器。Spring提供了IOC容器的两种实现方式:
1. BeanFactory
这是IOC容器的基本实现,是Spring内部使用的接口。面向Spring本身,不提供给开发人员使用。
2. ApplicationContext
BeanFactory的子接口,提供了更多高级特性。面向Spring得使用者,几乎所有场合都使用 ApplicationContext,而不是底层的BeanFactory。
3. ApplicationContext的主要实现类
2.2基于XML管理bean
2.2.1实验一:入门案列
1.创建Meven Module
2.引入依赖
<dependencies>
<!--基于Maven依赖传递性,导入spring-context依赖即可导入当前所需要所有jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.创建类HelloWorld
4.创建Spring的配置文件
在resources目录创建Spring配置文件
点击Spring Config创建applicationContext.xml
5.在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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<!--
bean:配置一个bean对象,将对象交给IOC容器管理
属性:
id:bean的唯一表示,不能重复
class:设置bean对象所对应的类型
-->
<bean id="helloworld" class="com.spring.POJO.HelloWorld"></bean>
</beans>
6.创建测试类测试
@Test
public void test(){
//获取IOC容器
ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取IOC容器中的bean
HelloWorld helloWorld=(HelloWorld) ioc.getBean("helloworld");
helloWorld.sayHello();
}
2.2.2 实验二:获取bean
创建实体类Student:
public class Student{
private Integer sid;
private String sname;
private Integer age;
private String gender;
/*get/set/toString。。。*/
}
获取bean的三种方式:
1. 方式一:根据bean的id获取
@Test
public void IOCTest(){
//获取IOC
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
//获取bean
Student student=(Student) ioc.getBean("studentOne");
System.out.println(student);
}
}
2.方式二:根据bean的类型获取
@Test
public void IOCTest(){
//获取IOC
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
//获取bean
Student student=ioc.getBean(Student.class);
System.out.println(student);
}
3.方式三:根据bean的id和类型获取
/*
获取bean的三种方式:
1.根据bean的id获取
2.根据bean的类型获取
注意:根据类型获取bean时,要求IOC容器中有且只有一个类型匹配的bean
若没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException
若有多个类型匹配的bean,此时抛出异常:NoUniqueBeanDefinitionException
3.根据bean的id和类型获取
*/
@Test
public void IOCTest(){
//获取IOC
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
//获取bean
// Student student=(Student) ioc.getBean("studentOne");
// Student student=ioc.getBean(Student.class);
Student student=ioc.getBean("studentOne",Student.class);
System.out.println(student);
}
4.注意
当根据类型获取bean时,要求IOC容器中指定类型的bean有且只有一个
当IOC容器中一共配置了两个:
<bean id="studentOne" class="com.spring.POJO.Student"/>
<bean id="studentTwo" class="com.spring.POJO.Student"/>
根据类型获取时会抛出异常:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘com.spring.POJO.Student’ available: expected single matching bean but found 2: studentOne,studentTwo
5.扩展
如果组件实现了接口,根据接口类型可以获取bean吗?
可以,前提是bean唯一
创建Person接口:
public interface Person {
}
public class Student implements Person{
private Integer sid;
private String sname;
private Integer age;
private String gender;
public Student() {
}
/*get/set/toString。。。*/
测试类:
@Test
public void IOCTest(){
//获取IOC
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
//获取bean
Student student=ioc.getBean(Student.class);
System.out.println(student);
Person person=ioc.getBean(Person.class);
System.out.println(person);
}
如果一个接口有多个实现类,这些实现类都配置了bean,根据接口类型可以获取bean吗?
不行,因为bean不唯一
6.结论
根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:[对象instanceof指定的类型]的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。
2.2.3实验三:依赖注入setter注入
1.创建学生类Student
public class Student{
private Integer sid;
private String sname;
private Integer age;
private String gender;
public Student() {
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(Integer sid, String sname, Integer age, String gender) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.gender = gender;
}
}
2.配置bean时为属性赋值
<bean id="studentOne" class="com.spring.POJO.Student"/>
<bean id="studentTwo" class="com.spring.POJO.Student">
<!--
property:通过成员变量的set方法进行赋值
name:设置需要赋值的属性名(和set方法有关)
value:设置属性所赋的值
-->
<property name="sid" value="1001"/>
<property name="sname" value="小明"/>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
3.测试
@Test
public void DITest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Student student=ioc.getBean("studentTwo",Student.class);
System.out.println(student);
}
2.2.4实验四:依赖注入之构造器注入
1.在Student类中添加有参构
public Student(Integer sid, String sname, Integer age, String gender) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.gender = gender;
}
2.配置bean
<!--
constructor-arg标签还有两个属性可以进一步描述构造参数
index属性:指定参数所在的位置的索引(从0开始)
name属性:指定参数名
-->
<bean id="studentThree" class="com.spring.POJO.Student">
<constructor-arg value="1002"/>
<constructor-arg value="爱丽丝"/>
<constructor-arg value="女"/>
<constructor-arg value="24" name="score"/>
</bean>
3.测试
@Test
public void DI1Test(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Student student=ioc.getBean("studentThree",Student.class);
System.out.println(student);
}
2.2.5实验五:特殊值处理
1.字面量赋值
什么是字面量?
int a=10;
声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a的时候,我们实际上拿到的值是10。
而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。
<!--使用value属性给bean的属性赋值时,Spring会把value属性的值看做字面量-->
<property name="sname" value="小明"/>
2.null值
<property name="sname">
<null/>
</property>
注意:
<property name="sname" value="null"/>
以上写法,为name所赋的值是字符串null
3.xml实体
<!--解决方案一:使用XML实体来代替(a<b)-->
<property name="expression" value="a < b"/>
4.CDATA节
<!--
CDATA节其中的内容会原样解析
XML解析器看到CDATA节就知道这里是纯文本,就不会当作XML标签或属性来解析
-->
<property name="sname">
<value><![CDATA[<Tom>]]></value>
</property>
2.2.6实验六:为类类型属性赋值
1.创建班级类Clazz
public class Clazz {
private Integer clazzId;
private String clazzName;
public Clazz() {
}
public Clazz(Integer clazzId, String clazzName) {
this.clazzId = clazzId;
this.clazzName = clazzName;
}
@Override
public String toString() {
return "Clazz{" +
"clazzId=" + clazzId +
", clazzName='" + clazzName + '\'' +
'}';
}
public Integer getClazzId() {
return clazzId;
}
public void setClazzId(Integer clazzId) {
this.clazzId = clazzId;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
}
2.修改Student类
public class Student{
private Integer sid;
private String sname;
private Integer age;
private String gender;
private Double score;
private Clazz clazz;
/* get/set/toString...*/
}
3.方式一:引用外部已声明的bean
<bean id="StudentFive" class="com.spring.POJO.Student">
<property name="sid" value="100"/>
<property name="sname" value="小琼"/>
<property name="age" value="22"/>
<property name="gender" value="女"/>
<property name="score" value="100"/>
<!--
ref:引用IOC容器中的某个bean的id
-->
<property name="clazz" ref="clazzOne"></property>
</bean>
<bean id="clazzOne" class="com.spring.POJO.Clazz">
<property name="clazzId" value="11"/>
<property name="clazzName" value="奥赛班"/>
</bean>
4.方式二:内部bean
<bean id="StudentFive1" class="com.spring.POJO.Student">
<property name="sid" value="100"/>
<property name="sname" value="小琼"/>
<property name="age" value="22"/>
<property name="gender" value="女"/>
<property name="score" value="100"/>
<!--
内部bean,只能在当前bean的内部使用,不能直接通过IOC容器获取
-->
<property name="clazz">
<bean id="clazzInner" class="com.spring.POJO.Clazz">
<property name="clazzId" value="33"/>
<property name="clazzName" value="普通班"/>
</bean>
</property>
</bean>
测试类:
@Test
public void DITest1(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Student student=ioc.getBean("StudentFive1",Student.class);
System.out.println(student);
}
5.方式三:级联属性赋值
<bean id="StudentFive" class="com.spring.POJO.Student">
<property name="sid" value="100"/>
<property name="sname" value="小琼"/>
<property name="age" value="22"/>
<property name="gender" value="女"/>
<property name="score" value="100"/>
<!--
ref:引用IOC容器中的某个bean的id
-->
<property name="clazz" ref="clazzOne"></property>
<!--级联方式,要保证提前为clazz属性赋值或者实例化-->
<property name="clazz.clazzId" value="22"/>
<property name="clazz.clazzName" value="重点班"/>
</bean>
<bean id="clazzOne" class="com.spring.POJO.Clazz">
<property name="clazzId" value="11"/>
<property name="clazzName" value="奥赛班"/>
</bean>
2.2.7实验七:为数组类型属性赋值
1.修改Student类
在Student类中添加以下代码:
private String[] hobbies;
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
/*重写toString*/
2.配置bean
<property name="hobbies">
<array>
<value>足球</value>
<value>篮球</value>
<value>羽毛球</value>
</array>
</property>
2.2.8实验八:为集合类型属性赋值
1.为List集合类型属性赋值
public class Clazz {
private Integer clazzId;
private String clazzName;
private List<Student> students;
/*get/set/toString*/
}
方法一:
<bean id="clazz1" class="com.spring.POJO.Clazz">
<property name="clazzId" value="11"/>
<property name="clazzName" value="奥赛班"/>
<property name="students">
<list>
<ref bean="studentOne"/>
<ref bean="studentTwo"/>
</list>
</property>
</bean>
方法二:
<bean id="clazz2" class="com.spring.POJO.Clazz">
<property name="clazzId" value="11"/>
<property name="clazzName" value="奥赛班"/>
<property name="students" ref="studentList"/>
</bean>
<!--配置一个集合类型的bean,需要使用util的约束-->
<util:list id="studentList">
<ref bean="studentOne"/>
<ref bean="studentTwo"/>
</util:list>
测试类:
@Test
public void DIClazz1Test(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Clazz clazz=ioc.getBean("clazz1",Clazz.class);
System.out.println(clazz);
}
@Test
public void DIClazz2Test(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Clazz clazz=ioc.getBean("clazz2",Clazz.class);
System.out.println(clazz);
}
2.为Map集合类型属性赋值
创建Teache实体类:
public class Teacher {
private Integer tid;
private String tname;
public Teacher() {
}
@Override
public String toString() {
return "Teacher{" +
"tid=" + tid +
", tname='" + tname + '\'' +
'}';
}
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public Teacher(Integer tid, String tname) {
this.tid = tid;
this.tname = tname;
}
}
在Student实体类中添加:
private Map<String ,Teacher> teacherMap;
/*get/set/toStrign...*/
bean.xml
<property name="teacherMap">
<map>
<entry key="1008" value-ref="teacherOne"/>
<entry key="1009" value-ref="teacherTwo"/>
</map>
</property>
<bean id="teacherOne" class="com.spring.POJO.Teacher">
<property name="tid" value="1008"/>
<property name="tname" value="万教授"/>
</bean>
<bean id="teacherTwo" class="com.spring.POJO.Teacher">
<property name="tid" value="1008"/>
<property name="tname" value="王教授"/>
</bean>
3.引用集合类型的bean
<property name="teacherMap" ref="teacherMap"/>
<util:map id="teacherMap">
<entry key="1008" value-ref="teacherOne"/>
<entry key="1009" value-ref="teacherTwo"/>
</util:map
2.2.9实验九:p命名空间
<bean id="studentSix" class="com.spring.POJO.Student"
p:sid="1005" p:sname="小黑" p:teacherMap-ref="teacherMap"/>
测试类:
@Test
public void DIstudentSixTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Student student=ioc.getBean("studentSix",Student.class);
System.out.println(student);
}
2.2.10实验十:引入外部属性文件
1.加入依赖
<!-- 数据源依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
2.创建外部属性文件
创建spring-datasource.xml
3.引入属性文件
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=数据库密码
spring-datasource.xml:
<!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
4.配置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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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">
<!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
5.测试
//测试是否连接数据库
@Test
public void DataSourceTest() throws SQLException {
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-datasource.xml");
DruidDataSource dataSource=ioc.getBean(DruidDataSource.class);
System.out.println(dataSource.getConnection());
}
2.2.11实验十一:bean的作用域
1.概念
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,个取值含义参加下表:
取值 | 含义 | 创建对象时机 |
singleton(默认) | 在IOC容器中,这个bean的对象始终为单例 | 容器初始化的时候创建 |
prototype | 原型模式,获取创建的都是新的对象 | 从容器当中获取的时候创建 |
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
取值 | 含义 |
request | 在一个请求范围内有效 |
prototype | 在一个会话范围内有效 |
2.创建User类
package com.spring.POJO;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
}
3.配置bean
<!--
scope:设置bean的作用域
scope="singleton|prototype"
-->
<bean id="user" class="com.spring.POJO.User" scope="singleton">
<property name="id" value="1001"/>
<property name="username" value="管理"/>
<property name="age" value="23"/>
</bean>
4.测试
@Test
public void ScopeTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-scop.xml");
User user1=ioc.getBean("user",User.class);
User user2=ioc.getBean("user",User.class);
System.out.println(user1==user2);
}
2.2.12实验十二:bean的生命周期
1.具体的生命周期过程
- bean对象创建(调用无参构造器)
- 给bean对象设置属性
- bean对象初始化之前操作(由bean的后置处理器负责)
- bean对象初始化(需在配置bean时指定初始化方法)
- bean对象初始化之后操作(由bean的后置处理器负责)
- bean对象就绪可以使用
- bean对象销毁(需在配置bean时指定销毁方法)
- IOC容器关闭
2.修改User类
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
System.out.println("生命周期1:实例化");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
System.out.println("声明周期2:依赖注入");
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public void initMethod(){
System.out.println("生命周期3:初始化");
}
public void destroyMethod(){
System.out.println("生命周期4:销毁");
}
}
3.配置bean
<bean id="user" class="com.spring.POJO.User" init-method="initMethod" destroy-method="destroyMethod">
<property name="id" value="1001"/>
<property name="username" value="admin"/>
<property name="password" value="123456"/>
<property name="age" value="23"/>
</bean>
4.测试
/*
1.实例化
2.依赖注入
3.初始化,需要通过bean的init-method属性指定初始化的方法
4.IOC容器关闭时销毁,需要通过bean的destroy-method属性指定销毁的方法
注意:
若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行
若bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行
*/
@Test
public void test(){
//ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法
ConfigurableApplicationContext ioc=new ClassPathXmlApplicationContext("spring-lifecycle.xml");
User user=ioc.getBean(User.class);
System.out.println(user);
ioc.close();
}
5.bean的后置处理器
bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器种所有bean都会执行
创建bean的后置处理器:
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之前调用 --> postProcessBeforeInitialization");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之后调用 --> postProcessAfterInitialization");
return bean;
}
}
<bean id="myBeanPostProcessor" class="com.spring.Process.MyBeanPostProcessor">
</bean>
2.2.13实验十三:FactoryBean
1.简介
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。
ublic interface FactoryBean<T> {
String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
@Nullable
T getObject() throws Exception;
@Nullable
Class<?> getObjectType();
default boolean isSingleton() {
return true;
}
}
2.创建UserFactoryBean类
public class UserFactoryBean implements FactoryBean<User> {
@Override
public User getObject() throws Exception {
return new User();
}
@Override
public Class<?> getObjectType() {
return User.class;
}
}
3.配置bean
<bean class="com.spring.factory.UserFactoryBean"></bean>
4.测试
/*
FactoryBean是一个接口,需要创建一个类实现该接口
其中有三个方法:
getObject():通过一个对象交给IOC容器管理
getObjectType():设置所提供的类型
isSingleton():所提供的对象是否单例
当把FactoryBean的实现类配置为bean时,会将当前类中的getObject()所返回的对象交给IOC容器管理
*/
@Test
public void FactoryBeanTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-factory.xml");
User user=ioc.getBean(User.class);
System.out.println(user);
}
2.2.14实验十四:基于XML的自动装配
1.创建模拟
自动装配:
根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型的赋值属性
创建UserController:
public class UserController {
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public void saveUser(){
userService.saveUser();
}
}
Service/UserService接口:
public interface UserService {
void saveUser();
}
Service/impl/UserServiceImpl:
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void saveUser() {
userDao.saveUser();
}
}
Dao/UserDao接口:
public interface UserDao {
void saveUser();
}
Dao/impl/UserDaoImpl:
public class UserDaoImpl implements UserDao {
@Override
public void saveUser() {
System.out.println("保存成功!");
}
}
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-4.2.xsd">
<bean id="userController" class="com.spring.Controller.UserController">
<property name="userService" ref="userService"/>
</bean>
<bean id="userService" class="com.spring.Service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.spring.Dao.impl.UserDaoImpl">
</bean>
</beans>
3.测试
@Test
public void AutoWireTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("spring-autowire-xml.xml");
UserController userController=ioc.getBean(UserController.class);
userController.saveUser();
}
自动装配:
根据指定的策略,在IOC容器中匹配某个bean,自动为bean中的类类型的属性或接口的属性赋值
可以通过bean标签中的autowire属性设置自动装配的策略
自动装配的策略:
1. no,default:表示不装配,即bean中的属性不会自动匹配某个bean为属性赋值,此时属性使用默认值
2.byType,byName:根据要赋值的属性的类型,在IOC容器中匹配某个bean,为属性赋值
注意:
1.若通过类型没有找到任何一个类型匹配的bean,此时不装配,属性使用默认值
2.若通过类型找到了很多个类型匹配的bean,此时会抛出异常
3.byName:将要赋值的属性的属性名作位bean的id在IOC容器中匹配某个bean,为属性赋值
总结:但匹配类型的bean有多个时,此时可以使用byName实现自动装配
总结:但是用byType实现自动装配时,IOC容器中有且只有一个匹配类型的bean能够为属性赋值
- 自动装配之byType:
<bean id="userController" class="com.spring.Controller.UserController" autowire="byType">
<!--<property name="userService" ref="userService"/>-->
</bean>
<bean id="userService" class="com.spring.Service.impl.UserServiceImpl" autowire="byType">
<!--<property name="userDao" ref="userDao"/>-->
</bean>
<bean id="userDao" class="com.spring.Dao.impl.UserDaoImpl">
</bean>
- 自动装配之byName
<bean id="userController" class="com.spring.Controller.UserController" autowire="byName">
<!--<property name="userService" ref="userService"/>-->
</bean>
<bean id="userService" class="com.spring.Service.impl.UserServiceImpl" autowire="byName">
<!--<property name="userDao" ref="userDao"/>-->
</bean>
<bean id="userDao" class="com.spring.Dao.impl.UserDaoImpl" autowire="byName">
</bean>
2.3基于注解管理bean
2.3.1实验一:标记与扫描
1.注解
和XML配置文件一样,注解本身并不能执行,注解本身仅仅只是一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。
本质上:所有一切的操作都是java代码来完成的,XML和注解只是告诉框架中的java代码如何执行。
2.扫描
Spring为了知道程序员在那些地方标记了什么注解,就需要通过扫描的方式,来进行检测,然后根据注解进行后续操作。
3.新建Maven Module
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
4.创建Spring配置文件
5.标识组件的常用注解
@Component : 将类标识为普通组件
@Controller:将类标识为控制层组件
@Service:将类标识为业务层组件
@Repository: 将类标识为持久层组件
问:以上四个注解有什么关系和区别?
通过查看源码我们得知,@Controller,@Service,@Repository者三个注解只是在@Component注解的基础上起的三个新名字。
对于Spring使用IOC容器管理这些组件莱说没有区别。所以@Controller,@Service,@Repository这三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。
注意:虽然它们本质上一致,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。
6.创建组件
创建控制层组件
@Controller
public class UserController {
}
创建接口UserService
public interface UserService {
}
创建UserServiceImpl
package com.spring.Service.impl;
import com.spring.Service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
}
创建UserDao接口
public interface UserDao {
}
创建UserDaoImpl
@Repository
public class UserDaoImpl implements UserDao {
}
7.扫描组件
情况一:最基本的扫描方式
<context:component-scan base-package="com.spring">
</context:component-scan>
情况二:指定要排除的组件
<context:component-scan base-package="com.spring">
<!--context:exclude-filter标签:指定排除规定-->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置派出的类型的全类名
-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<!--<context:exclude-filter type="assignable" expression="com.spring.Controller.UserController"/>-->
</context:component-scan>
情况三:仅扫描指定组件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描组件-->
<context:component-scan base-package="com.spring" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<!--context:exclude-filter标签:指定排除规定-->
<!--
type:设置排除或包含的依据
type="annotation",根据注解排除,expression中设置要排除的注解的全类名
type="assignable",根据类型排除,expression中设置派出的类型的全类名
context:include-filter:包含扫描
注意:需要在context:component-scan标签中设置use-default-filters="false"
use-default-filters="false",所设置的包下所有的类都需要扫描,此时可以使用排除扫描
use-default-filters="true",所设置的包下所有的类都不需要扫描,此时可以使用包含扫描
-->
<!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!--<context:exclude-filter type="assignable" expression="com.spring.Controller.UserController"/>-->
</context:component-scan>
</beans>
8.测试
@Test
public void IOCByAnnotationTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
UserController userController=ioc.getBean(UserController.class);
System.out.println(userController);
UserService service=ioc.getBean(UserService.class);
System.out.println(service);
UserDao dao=ioc.getBean(UserDao.class);
System.out.println(dao);
}
9.组件所对应的bean的id
可以通过标识组件的注解的value属性值设置bean的自定义的id
@Controller("controller")
public class UserController {
}
2.3.2实验二:基于注解的自动装配
1.场景模拟
创建service/dao/controller和impl层
2.@Autowried注解
@AutoWired:实现自动装配功能的注解
1.@AutoWired注解能够标识的位置
a>标识在成员变量上,此时不需要设置成员变量的set方法
b>标识在set方法上
c>为当前成员变量赋值的有参构造上
2.@AutoWired注解的原理
a>默认通过byType的方式,在IOC容器中通过类型匹配某个bean为属性赋值
b>若有多个类型匹配的bean,此时会自动转换为byName的方式实现自动装配的效果
即将要赋值的属性的属性名作为bean的id匹配某个bean为属性赋值
c>若byType和byName的方式都无法实现自动装配,即IOC容器中有多个类型匹配的bean
且这些bean的id和要赋值的属性的属性名都不一致,此时抛出异常
d>此时可以在要复制的属性上,添加一个注解@Qualifier
通过该注解的value属性值,指定某个bean的id,将这个bean为属性赋值
@ Qualifier 注解原理
当发生 @Autowired 的情况的时候,可以自己指定bean的id
@Controller
public class UserController {
@Autowired
@Qualifier("userService")
private UserService service;
}
@Autowired中有属性required,默认值为true,因此在自动装配无法找到相应的bean时,会装配失败,可以将属性required的值设置为true,则表示能装就装,装不上就不装,此时自动装配的属性为默认值,但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。
3.AOP
3.1场景模拟
3.1.1声明接口
声明计算机接口Calculator,包含加减乘除的抽象方法
public interface Calculator {
int add(int i,int j);
int sub(int i,int j);
int mul(int i,int j);
int div(int i,int j);
}
3.1.2创建实现类
public class CalculatorImpl implements Calculator {
@Override
public int add(int i, int j) {
int result=i+j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int sub(int i, int j) {
int result=i-j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int mul(int i, int j) {
int result=i*j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int div(int i, int j) {
int result=i/j;
System.out.println("内部方法,result:"+result);
return result;
}
}
3.1.3创建带日志功能的实现类
public class CalculatorImpl implements Calculator {
@Override
public int add(int i, int j) {
System.out.println("日志,方法:add,参数:"+i+","+j);
int result=i+j;
System.out.println("内部方法,result:"+result);
System.out.println("日志,方法:add,结果:"+result);
return result;
}
@Override
public int sub(int i, int j) {
System.out.println("日志,方法:sub,参数:"+i+","+j);
int result=i-j;
System.out.println("内部方法,result:"+result);
System.out.println("日志,方法:sub,结果:"+result);
return result;
}
@Override
public int mul(int i, int j) {
System.out.println("日志,方法:mul,参数:"+i+","+j);
int result=i*j;
System.out.println("内部方法,result:"+result);
System.out.println("日志,方法:mul,结果:"+result);
return result;
}
@Override
public int div(int i, int j) {
System.out.println("日志,方法:div,参数:"+i+","+j);
int result=i/j;
System.out.println("内部方法,result:"+result);
System.out.println("日志,方法:div,结果:"+result);
return result;
}
}
3.1.4提出问题
1.现有代码缺陷
针对带日志功能的实现类,我们发现有如下缺陷:
(1)对核心业务功能有干扰,导致程序员在开发核心业务功能时分散了精力
(2)附加功能分散在各个业务功能方法中,不利于统一维护
2.解决思路
解决这两个问题,核心就是:解耦。我们需要把附加功能从业务功能代码中抽取出来。
3.困难
解决问题的困难,要抽取的代码在方法内部,靠以前把子类中的重复代码抽取到父类的方法设法解决,所以要引入新的技术。
3.2代理模式
3.2.1概念
1.介绍
二十三种设计模式的一种,属于结构型模式。它的作用就是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接对目标进行调试,而是通过代理类间接调用。让不属于目标方法核心逻辑的代码从目标方法种剥离出来一一解耦。调用目标方法时先调用呆莉对象的方法,减少对目标方法的调用和打扰,同使让附加功能能够集中在一起也有利于统一维护。
2.相关术语
代理:将非核心逻辑剥离出来以后,封装这些非核心逻辑的类,对象,方法。
目标:被代理“套用”了非核心逻辑代码的类,对象,方法。
3.2.2静态代理
创建静态代理类:
package com.spring.Proxy;
import com.spring.Proxy.impl.CalculatorImpl;
public class CalculatorStaticProxy implements Calculator{
private CalculatorImpl target;
public CalculatorStaticProxy(CalculatorImpl target) {
this.target = target;
}
@Override
public int add(int i, int j) {
System.out.println("日志,方法:add,参数:"+i+","+j);
int result=target.add(i,j);
System.out.println("日志,方法:add,结果:"+result);
return result;
}
@Override
public int sub(int i, int j) {
System.out.println("日志,方法:sub,参数:"+i+","+j);
int result=target.sub(i,j);
System.out.println("日志,方法:sub,结果:"+result);
return result;
}
@Override
public int mul(int i, int j) {
System.out.println("日志,方法:mul,参数:"+i+","+j);
int result=target.mul(i,j);
System.out.println("日志,方法:mul,结果:"+result);
return result;
}
@Override
public int div(int i, int j) {
System.out.println("日志,方法:div,参数:"+i+","+j);
int result=target.div(i,j);
System.out.println("日志,方法:div,结果:"+result);
return result;
}
}
静态代理确实实现了解耦,但是由于代码都写死了,完全不具备任何的灵活性.就拿日志功能来说,将来其他地方需要附加日志,那还得在声明多个静态代理类,那就产生了大量重复代码,日志功能还是分散的,没有统一管理。
提出进一步的需求:将日志功能集中到一个代理类中,将来有任何的日志需求,都通过这一个代理类来实现。这就需要使用动态代理技术了。
测试类:
@Test
public void ProxyTest(){
CalculatorStaticProxy proxy=new CalculatorStaticProxy(new CalculatorImpl());
proxy.add(1,2);
proxy.div(2,5);
proxy.mul(4,2);
proxy.sub(8,2);
}
3.2.3动态代理
生产代理对象的工厂类:
public class ProxyFactory {
private Object target;
public ProxyFactory(Object target) {
this.target = target;
}
public Object getTarget(){
/*
ClassLoader classLoader:指定加载动态生成的代理类的类加载器
Class[] interfaces:获取目标对象实现的所有接口的class对象的数组
InvocationHandler handler:设置迪阿尼内中的抽象方法如何重写
*/
ClassLoader classLoader=this.getClass().getClassLoader();
Class<?>[] interfaces=target.getClass().getInterfaces();
InvocationHandler handler=new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("日志,方法:"+method.getName()+"参数:"+ Arrays.toString(args));
//proxy:表示代理对象,method表示要执行的方法,args表示要执行的方法的参数列表
Object result=method.invoke(target,args);
System.out.println("日志,方法:"+method.getName()+"结果:"+result);
return result;
}
};
return Proxy.newProxyInstance(classLoader,interfaces,handler);
}
}
3.2.4测试
/*
动态代理有两种:
1.jdk动态代理:要求必须要有接口,最终生成的代理类和目标类实现相同的接口
2.cglib动态代理,最终生成的代理类会继承目标类,并且和目标类在相同的包下
*/
@Test
public void testProxy(){
ProxyFactory proxyFactory=new ProxyFactory(new CalculatorImpl());
Calculator calculator=(Calculator)proxyFactory.getTarget();
calculator.add(1,2);
}
3.3AOP概念及相关术语
3.3.1概述
AOP是一种设计思想,时软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现现在不修改代码的情况下给程序动态统一添加额外功能的一种技术。
3.3.2相关术语
1.横切关注点
从那个方法中抽取出来的同一类非核心业务。在同一个项目中,我们可以使用多个横切关注点对相关方法进行多个不同方面的增强。
这个概念不是语法层面天然存在的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横切关注点。
2.通知
每个 横切关注点 都需要对应一个方法实现, 这样的切面类方法就叫通知方法。
3.切面
封装通知方法的类。
4.目标
被代理的目标对象。
5.代理
向目标对象引用通知之后创建的代理对象。
6.连接点
这也是一个纯逻辑概念,不是语法定义。
把方法排成一排,每一个横切位置看成X轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。
7.切入点
定位连接点的方式。
每个类的方法中都包含多个连接点,所以连接点是类中客观存在的事务。
如果把连接点看作数据库中的记录,那么切入点就是查询记录的SQL语句。
Spring的AOP技术可以通过切入点定位到特定的连接点。
切点通过org.springframework.aop.Pointcut接口进行描述,它使用类和方法作位连接点的查询条件。
3.3.3作用
简化代码:把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。
代码增强:把特定的功能封装到切面类中,看哪里需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。
3.4基于注解的AOP
3.4.1技术说明
动态代理:JDK原生的实现方式,需要被代理的目标类必须实现接口,因为这个技术要求代理对象和目标对象实现同样的接口
cglib:通过继承被代理的目标类实现代理,所以不需要目标实现接口
AspectJ:本质上是静态代理,将代理逻辑"织入""被代理的目标类编译得到的字节码文件,所以最终效果是动态的,weaver就是织入器,Spring只是借用了Aspect中的注解
3.4.2准备工作
1.添加依赖
在IOC所需依赖基础上再加入下面依赖即可:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
2.准备被代理的目标资源
接口:
public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}
实现类:
public class CalculatorImpl implements Calculator {
@Override
public int add(int i, int j) {
int result=i+j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int sub(int i, int j) {
int result=i-j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int mul(int i, int j) {
int result=i*j;
System.out.println("内部方法,result:"+result);
return result;
}
@Override
public int div(int i, int j) {
System.out.println("日志,方法:div,参数:"+i+","+j);
int result=i/j;
System.out.println("内部方法,result:"+result);
System.out.println("日志,方法:div,结果:"+result);
return result;
}
}
3.4.3创建切面类并配置
/*
在切面中,需要通过指定得注解将方法标识为通知方法
@Before:前置通知,在目标对象方法执行之前执行
*/
@Component
@Aspect //将当前组件标识为切面
public class LoggerAspect {
@Before("execution(public int com.spring.aop.Annotation.Calculator.add(int,int))")
public void beforeAdviceMethod(){
System.out.println("LoggerAspect ,前置通知");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--
AOP的注意事项:
切面类和注意事项都需要交给IOC容器管理
切面类必须通过@Aspect注解标识为一个切面
在Spring的配置文件中设置<aop:aspectj-autoproxy/>开启基于注解的AOP
-->
<context:component-scan base-package="com.spring.aop.Annotation"/>
<!--开启基于注解的AOP-->
<aop:aspectj-autoproxy/>
</beans>
3.4.4各种通知
public class AOPTest {
@Test
public void AOPByAnnotationTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean.xml");
Calculator calculator=ioc.getBean(Calculator.class);
calculator.add(1,1);
}
}
执行结果:
LoggerAspect ,前置通知
内部方法,result:2
在切面中,需要通过指定得注解将方法标识为通知方法
@Before:前置通知,在目标对象方法执行之前执行
@After:后置通知,在目标对象方法的finally子句中执行
@AfterReturning:返回通知,在目标对象方法返回值之后执行
@AfterThrowing:异常通知,在目标对象方法的catch字句中执行
各种通知的执行顺序:
- Spring版本5.3.x以前:
- 前置通知
- 目标操作
- 后置通知
- 返回通知或异常通知
- Spring版本5.3.x以后:
- 前置通知
- 目标通知
- 返回通知或异常通知
- 后置通知
3.4.5切入点表达式语法
1.作用
切入点表达式:设置在标识通知的注解的value属性中
execution(public int com.spring.aop.Annotation.CalculatorImpl.add(int,int))
execution(* com.spring.aop.Annotation.CalculatorImpl.*(…))
第一个✳表示任意的访问修饰符和返回值类型
第二个✳表示类中任意的方法
…表示任意的参数列表
内的地方也可以使用✳,表示包下所有的类
2.语法细节
@Before("execution(* com.spring.aop.Annotation.Calculator.*(..))")
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应方法的签名信息
Signature signature=joinPoint.getSignature();
//获取连接点所对应方法的参数
Object[] args=joinPoint.getArgs();
System.out.println("LoggerAspect ,方法:"+signature.getName()+"参数,"+ Arrays.toString(args));
}
3.4.6重用切入点表达式
1.声明
@Pointcut("execution(* com.spring.aop.Annotation.Calculator.*(..))")
public void pointCut(){
}
2.在同一个切面中使用
@Before("pointCut()")
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应方法的签名信息
Signature signature=joinPoint.getSignature();
//获取连接点所对应方法的参数
Object[] args=joinPoint.getArgs();
System.out.println("LoggerAspect ,方法:"+signature.getName()+"参数,"+ Arrays.toString(args));
}
3.在不同切面中使用
@Component
@Aspect
public class validateAspect {
//@Before("execution(* com.spring.aop.Annotation.*(..))")
@Before("com.spring.aop.Annotation.LoggerAspect.pointCut()")
public void beforeMethod(){
System.out.println("validateAspect-->前置通知");
}
}
3.4.7获取通知的相关信息
返回通知获得返回值
/*
在返回通知中若要获取目标对象方法的返回值
只需要通过@AfterReturning注解的returning属性
就可以将通知方法的某个参数指定为接收目标对象方法的返回值的参数
*/
@AfterReturning(value = "pointCut()",returning = "result")
public void AfterReturningAdviceMethod(JoinPoint joinPoint,Object result){
Signature signature=joinPoint.getSignature();
System.out.println("LoggerAspect ,方法:"+signature.getName()+",结果:"+result);
}
异常通知获取异常
/*
在返回通知中若要获取目标对象方法的异常
只需要通过@AfterThrowing注解的throwing属性
就可以将通知方法的某个参数指定为接收目标对象方法出现的异常的参数
*/
@AfterThrowing(value = "pointCut()",throwing = "ex")
public void AfterThrowingAdviceMethod(JoinPoint joinPoint,Throwable ex){
Signature signature=joinPoint.getSignature();
System.out.println("LoggerAspect ,方法:"+signature.getName()+",异常通知"+ex);
}
环绕通知
@Around("pointCut()")
//环绕通知的方法一定要和目标对象方法的返回值一致
public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint){
Object result=null;
try {
System.out.println("环绕通知-->前置通知");
//表示目标对象方法的执行
result=joinPoint.proceed();
System.out.println("环绕通知-->返回通知");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("环绕通知-->异常通知");
}finally {
System.out.println("环绕通知-->后置通知");
}
return result;
}
3.4.8切面的优先级:
可以通过@Order注解的value属性设置优先级,默认值Interger的最大值
@Order注解的value属性值越小,优先级越高
@Component
@Aspect
@Order(1) //优先级(数字越小优先级越高)
public class validateAspect {
//@Before("execution(* com.spring.aop.Annotation.*(..))")
@Before("com.spring.aop.Annotation.LoggerAspect.pointCut()")
public void beforeMethod(){
System.out.println("validateAspect-->前置通知");
}
}
3.5基于Xml的AOP实现
LoggerAspect类:
@Component
public class LoggerAspect {
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应方法的签名信息
Signature signature=joinPoint.getSignature();
//获取连接点所对应方法的参数
Object[] args=joinPoint.getArgs();
System.out.println("LoggerAspect ,方法:"+signature.getName()+"参数,"+ Arrays.toString(args));
}
public void AfterAdviceMethod(JoinPoint joinPoint){
Signature signature=joinPoint.getSignature();
System.out.println("LoggerAspect ,方法:"+signature.getName()+",执行完毕!");
}
/*
在返回通知中若要获取目标对象方法的返回值
只需要通过@AfterReturning注解的returning属性
就可以将通知方法的某个参数指定为接收目标对象方法的返回值的参数
*/
public void AfterReturningAdviceMethod(JoinPoint joinPoint,Object result){
Signature signature=joinPoint.getSignature();
System.out.println("LoggerAspect ,方法:"+signature.getName()+",结果:"+result);
}
/*
在返回通知中若要获取目标对象方法的异常
只需要通过@AfterThrowing注解的throwing属性
就可以将通知方法的某个参数指定为接收目标对象方法出现的异常的参数
*/
public void AfterThrowingAdviceMethod(JoinPoint joinPoint,Throwable ex){
Signature signature=joinPoint.getSignature();
System.out.println("LoggerAspect ,方法:"+signature.getName()+",异常通知"+ex);
}
//环绕通知的方法一定要和目标对象方法的返回值一致
public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint){
Object result=null;
try {
System.out.println("环绕通知-->前置通知");
//表示目标对象方法的执行
result=joinPoint.proceed();
System.out.println("环绕通知-->返回通知");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("环绕通知-->异常通知");
}finally {
System.out.println("环绕通知-->后置通知");
}
return result;
}
}
bean_xml.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--扫描组件-->
<context:component-scan base-package="com.spring.aop.xml"></context:component-scan>
<aop:config>
<!--设置一个公共的切入点表达式-->
<aop:pointcut id="pointCut" expression="execution(* com.spring.aop.xml.CalculatorImpl.*(..))"/>
<!--将IOC容器中的某个bean设置为切面-->
<aop:aspect ref="loggerAspect">
<aop:before method="beforeAdviceMethod" pointcut-ref="pointCut"></aop:before>
<aop:after method="AfterAdviceMethod" pointcut-ref="pointCut"/>
<aop:after-returning method="AfterReturningAdviceMethod" returning="result" pointcut-ref="pointCut"/>
<aop:after-throwing method="AfterThrowingAdviceMethod" throwing="ex" pointcut-ref="pointCut"/>
<aop:around method="aroundAdviceMethod" pointcut-ref="pointCut"/>
</aop:aspect>
<aop:aspect ref="validateAspect" order="1">
<aop:after method="beforeMethod" pointcut-ref="pointCut"></aop:after>
</aop:aspect>
</aop:config>
</beans>
测试类:
@Test
public void AOPByXMLTest(){
ApplicationContext ioc=new ClassPathXmlApplicationContext("bean-xml.xml");
Calculator calculator=ioc.getBean(Calculator.class);
calculator.add(1,1);
}
4.声明式事务
4.1JdbcTemplate
4.1.1简介
Spring框架对JDBC进行封装,使用JdbcTempate方便实现对数据库操操作
4.1.2准备工作
1.加入依赖
<dependencies>
<!-- spring 核心: IOC 的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<!-- Spring jdbc 和 spring-tx 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.1</version>
</dependency>
<!-- Spring 整合Junit 的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>
2.创建jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
3.配置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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入jdbc.properties -->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!-- 数据源 : 其实添加的是其一个实现类 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 数据库信息 -->
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 连接池设置 -->
<property name="initialSize" value="10"></property>
<property name="maxActive" value="16"></property> <!-- 连接池最大活跃连接数 -->
</bean>
<!-- 注册 JDBCTemplate : 第三方Jar包使用不了注解 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
4.1.3测试
@RunWith(SpringJUnit4ClassRunner.class)
//设置Spring测试环境的配置文件
@ContextConfiguration("classpath:spring-jdbc.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testInsert(){
String sql="insert into t_user values (null,?,?,?,?,?)";
jdbcTemplate.update(sql,"root","123",23,"女","123@qq.com");
}
}
1.在测试类装配JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
2.测试增删改功能
//添加
@Test
public void testInsert(){
String sql="insert into t_user values (null,?,?,?,?,?)";
jdbcTemplate.update(sql,"root","123",23,"女","123@qq.com");
}
3.查询一条数据为实体类对象
@Test
public void TestGetUserById(){
String sql="select * from t_user where id=?";
User user=jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),1);
System.out.println(user);
}
4.查询多条数据为一个list集合
@Test
public void TestGetUserAll(){
String sql="select * from t_user";
List<User> users =jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
System.out.println(users);
}
5.查询单行单列的值
//count(*)
@Test
public void GetCountTest(){
String sql="select count(id) from t_user";
Integer count=jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println(count);
}
4.2声明式事务概念
4.2.1编程式事务
事务功能的相关操纵全部通过自己编写代码来实现
Connection con=....;
try{
//开启事务:关闭事务的自动提交
conn.setAutoCommit(false);
//核心操作
//提交事务
conn.commit();
}catch(Exception e){
//回滚事务
conn.rollBack();
}finally{
//释放数据库连接
conn.close();
}
编程式的实现方式存在缺陷:
细节没有屏蔽:具体操作过程中,所有细节都需要程序员自己来完成,比较繁琐
代码复用性不高:如果没有有效抽取出来,每次实现功能都需要自己编写代码,代码就没有得到复用
4.2.2声明式事务
既然事务控制的代码有规律可循,代码的结构基本是确定的,所以框架就可以将固定模式的代码收取出来,进行相关的封装
封装起来后,我们只需要在配置文件中进行简单的配置即可完成操作
- 好处1:提高开发效率
- 好处2:消除了冗余的代码
- 好处3:框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题,进行了健壮性,性能等各个方面的优化
所以,我们可以总结下面两个概念:
- 编程式:自己写代码实现功能
- 声明式:通过配置让框架实现功能
4.3基于注解的声明式事务
4.3.1准备工作
1.加入依赖
<dependencies>
<!-- spring 核心: IOC 的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<!-- Spring jdbc 和 spring-tx 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.1</version>
</dependency>
<!-- Spring 整合Junit 的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.1</version>
</dependency><dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.创建jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
3.配置Spring的配置文件
<!--扫描组件-->
<context:component-scan base-package="com.spring"></context:component-scan>
<!-- 引入jdbc.properties -->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!-- 数据源 : 其实添加的是其一个实现类 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 注册 JDBCTemplate : 第三方Jar包使用不了注解 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
4.创建表
t_book表:
t_user1表:
5.创建组件
创建BookController:
@Controller
public class BookController {
@Autowired
private BookService bookService;
public void BuyBook(Integer userId,Integer bookId){
bookService.BuyBook(userId,bookId);
}
}
创建BookDaoImpl:
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer getPriceByBookId(Integer bookId) {
String sql="select price from t_book where book_id=?";
return jdbcTemplate.queryForObject(sql,Integer.class,bookId);
}
@Override
public void updateStock(Integer bookId) {
String sql="update t_book set stock=stock-1 where book_id=?";
jdbcTemplate.update(sql,bookId);
}
@Override
public void updateBalance(Integer userId, Integer price) {
String sql="update t_user1 set balance=balance-? where user_id=?";
jdbcTemplate.update(sql,price,userId);
}
}
4.3.2测试无事务情况
1.创建测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-jdbc.xml")
public class TxByAnnotationTest {
@Autowired
private BookController bookController;
@Test
public void TestBuyBook(){
bookController.BuyBook(1,1);
}
}
2.模拟场景
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public void BuyBook(Integer userId, Integer bookId) {
//查询图书价格
Integer price=bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId,price);
}
}
4.3.3加入事务
1.添加事务配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">
<!--扫描组件-->
<context:component-scan base-package="com.spring"></context:component-scan>
<!-- 引入jdbc.properties -->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!-- 数据源 : 其实添加的是其一个实现类 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 注册 JDBCTemplate : 第三方Jar包使用不了注解 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启事务的注解驱动 :
将环绕通知作用到连接点上,即 @Transactional 标记的类 或 方法使用事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
2.添加事务注解
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
@Transactional
public void BuyBook(Integer userId, Integer bookId) {
//查询图书价格
Integer price=bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId,price);
}
}
4.3.4@Transactional注解标识的位置
声明式事务的配置步骤:
1.在Spring的配置文件中配置事务管理器
2.开启事务注解驱动
在需要被事务管理的方法上,添加@Transactional注解,该方法就会被事务管理器
@Transactional注解标识的位置:
1.标识在方法上
2.标识在类上,则类中所有的方法都会被事务管理
4.3.5事务属性:只读
1.介绍
对一个查询操作来说,如果我们把它设置成只读,就能够明确告诉数据库,这个操作不涉及写操作,这样数据库就能够针对查询操作来进行优化
2.使用方式
@Transactional(readOnly = true)
public void BuyBook(Integer userId, Integer bookId) {
//查询图书价格
Integer price=bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId,price);
}
3.注意
对增删改操作设置只读会出现异常
4.3.6事务属性:超时
1.介绍
事务在执行过程中,有可能因为遇到某些问题,导致程序卡住,从而长时间占用数据库资源,而长时间占用资源,大概率是因为程序运行出现了为标题(可能是java程序或MySQL数据库或望楼连接等等)此时这个很可能出现问题的程序应该被回滚,撤销它已做的操作,事务结束,把资源让出来,让其他正常程序可以执行
概括来说就是一句话:超时回滚,释放资源
2.使用方式
@Transactional(timeout = 3)
public void BuyBook(Integer userId, Integer bookId) {
//查询图书价格
Integer price=bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId,price);
}
4.3.7事务属性:回滚策略
1.介绍
声明式事务默认只针对运行时异常回滚,编译时异常不回滚
可以通过@Transactional中相关属性设置回滚策略
rollbackFor属性:需要设置一个Class类型的对象
rollbackForClassName属性:需要设置一个字符串类型的全类名
noRollbackFor属性:需要设置一个Class类型的对象
rollbackFor属性:需要设置一个字符串类型的全类名
2.使用方式
@Transactional(noRollbackFor = ArithmeticException.class)
public void BuyBook(Integer userId, Integer bookId) {
//查询图书价格
Integer price=bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId,price);
}
3.观察结果
虽然购买图书功能中出现了数学运算异常(ArithmeticException),但是我们设置的回滚策略是,当出现ArithmeticException不发生回滚,因此购买图书的操作正常执行
4.3.8事务属性:事务隔离级别
1.介绍
数据库系统必须具有隔离并发运行各个事务的能力,使它们不会相互影响,避免各种并发问题,一个事务与其他事务隔离的程度称为隔离级别,SQL标准中规定了多种事务隔离级别,不同隔离级别对应不同的干扰程度,隔离级别越高,数据一致性就越好,当并发性越弱。
隔离级别一共有四种:
- 读未提交:READ UNCOMMITTED
- 读已提交:READ COMMITTED
- 可重复读:REPEATABLE READ
- 串行化:SERIALIZABLE
2.使用方法
@Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
@Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
@Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
@Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
@Transactional(isolation = Isolation.SERIALIZABLE)//串行化
4.3.9事务属性:事务传播行为
1.介绍
当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行。
2.测试
创建接口CheckoutService:
public interface CheckoutService {
//结账
void checkout(Integer userId, Integer[] bookIds);
}
创建实现类CheckoutServiceImpl:
@Service
public class CheckoutServiceImpl implements CheckoutService {
@Autowired
private BookService bookService;
@Override
@Transactional
//一次购买多本图书
public void checkout(Integer userId, Integer[] bookIds) {
for(Integer bookId:bookIds){
bookService.BuyBook(userId,bookId);
}
}
}
在BookController中添加方法:
@Controller
public class BookController {
@Autowired
private CheckoutService checkoutService;
public void checkout(Integer userId,Integer[] bookIds){
checkoutService.checkout(userId,bookIds);
}
}
在数据库中将用户的余额修改为100元
3.观察结果
可以通过@Transactional中的propagation属性设置事务传播方式
修改BookServiceImpl中BuyBook()上,注解@Transactional的propagation属性
@Transactional(propagation=Propagation.REQUIRED),默认情况,表示如果当前线程上有已经开启的事务可用,那么就在这个事务中运行。经过观察,购买图书馆的方法BuyBook()在CheckOut()中被调用,CheckOut()上有事务注解,因此在此事务中执行。所购买的里昂本书的价格为80和50,而用户的余额为100,因此在购买第二本图书时余额不足失败,导致整个CheckOut()中回滚,即只要有一本书买不了,就都买不了。
@Transactional(propagation=Propagation.REQUIRES_NEW),表示不管当前线程上是否已经开启的事务,都要开启新事务。同样的场景,每次购买图书都是在BuyBook()的事务中执行,因此第一本书购买成功,事务结束,第二本图书购买失败,只在第二次的BuyBook()中回滚,购买第一本图书不受影响,即能买基本就买几本
4.4基于XML的声明式事务
4.3.1修改Spring配置文件
将Spring配置文件中去点tx:annotation-driven标签,并添加配置:
<!-- 配置事务的切面 -->
<aop:config>
<!-- 考虑到后面整合 SpringSecurity, 避免把 UserDetialsService 扫描到事务控制,因此让切入点表达式定位到 impl -->
<aop:pointcut id="txPointcut" expression="execution(* *..*ServiceImpl.*(..))"/>
<!-- 将切入点表达式 和 事务的通知关联起来 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- 配置事务的属性 -->
<tx:attributes>
<!-- 查询方法:配置只读属性,让数据库知道这是一个查询操作 -->
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<!-- 增删改查方法:配置下事务的传播行为、回滚异常
rollbackfor:
默认:运行时异常
建议:编译时异常和运行时异常都回滚.
-->
<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="batch*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
注意:基于XMl实现的声明事务,必须引入aspectj的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>