🍃Spring:
1. Spring:
1. 1、简介:
- Spring : 春天—>给软件行业带来了春天
- 2002 ,首次推出了Spring框架的雏形,interface21
- 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
- 很难想象Rod Johnson的学历 , 他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
- Spring理念 : 使现有技术更加实用 . 本身就是一个大杂烩 , 整合现有的框架技术。
- SSH:Struct2+Spring+Hibernate
- SSM:SpringMVC+Spring+Mybatis
官网:https://spring.io/
官方下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
官方文档:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html
GitHub:https://github.com/spring-projects/spring-framework/releases
导包:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.2、优点:
Spring是一个轻量级的**控制反转(IOC) ,面向切面编程(AOP)**的框架
- Spring是一个 开源的免费的框架(容器)!
- Spring是一个轻量级的,非入侵式的框架
- 控制反转(IOC) ,面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持
1.3、 组成:
1.4.、拓展:
在Spring 的官网有这个介绍:现代化的java开发,说白了就是基于Spring的开发
- Spring Boot:一个快速开发的脚手架。基于Spring Boot 可以快速开发单个微服务。约定大于配置
- Spring Cloud:基于SpringBoot 实现的
弊端:发展了太久之后,违背了原来的理念,配置十分繁琐,配置地狱
2. IOC理论推导:
1、先写一个UserDao接口
public interface UserDao {
public void getUser();
}
2、再去写Dao的实现类
public class UserDaoImpl implements UserDao {
@Override
public void getUser() {
System.out.println("获取用户数据");
}
}
3、然后去写UserService的接口
public interface UserService {
public void getUser();
}
4、最后写Service的实现类
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public void getUser() {
userDao.getUser();
}
}
5、测试一下
@Test
public void test(){
UserService service = new UserServiceImpl();
service.getUser();
}
这是我们原来的方式 , 开始大家也都是这么去写的对吧 . 那我们现在修改一下 .
把Userdao的实现类增加一个 .
public class UserDaoMySqlImpl implements UserDao {
@Override
public void getUser() {
System.out.println("MySql获取用户数据");
}
}
紧接着我们要去使用MySql的话 , 我们就需要去service实现类里面修改对应的实现
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoMySqlImpl();
@Override
public void getUser() {
userDao.getUser();
}
}
在假设, 我们再增加一个Userdao的实现类 .
public class UserDaoOracleImpl implements UserDao {
@Override
public void getUser() {
System.out.println("Oracle获取用户数据");
}
}
那么我们要使用Oracle , 又需要去service实现类里面修改对应的实现 . 假设我们的这种需求非常大 , 这种方式就根本不适用了, 甚至反人类对吧 , 每次变动 , 都需要修改大量代码 . 这种设计的耦合性太高了, 牵一发而动全身 .
那我们如何去解决呢 ?
我们可以在需要用到他的地方 , 不去实现它 , 而是留出一个接口 , 利用set , 我们去代码里修改下 .
public class UserServiceImpl implements UserService {
private UserDao userDao;
// 利用set实现
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
现在去我们的测试类里 , 进行测试 ;
@Test
public void test(){
UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoMySqlImpl() );
service.getUser();
//那我们现在又想用Oracle去实现呢
service.setUserDao( new UserDaoOracleImpl() );
service.getUser();
}
大家发现了区别没有 ? 可能很多人说没啥区别 . 但其实, 他们已经发生了根本性的变化 , 很多地方都不一样了 . 仔细去思考一下 , 以前所有东西都是由程序去进行控制创建 , 而现在是由我们自行控制创建对象 , 把主动权交给了调用者 . 程序不用去管怎么创建,怎么实现了 . 它只负责提供一个接口 .
这种思想 , 从本质上解决了问题 , 我们程序员不再去管理对象的创建了 , 更多的去关注业务的实现 . 耦合性大大降低 . 这也就是IOC的原型 !
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码,如果程序代码量十分大,修改一次的成本代价十分昂贵
我们使用一个Set接口实现,已经发生了革命性的变化
private UserDao userDao;
// 利用set进行动态实现值的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前,程序时主动创建对象,控制权在程序员手上
- 使用set注入后,程序员不再具有主动性,而是变成被动的接收对象
3. IOC本质:
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
4. HelloSpring:
- 实体类Hello:
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello"+name);
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
- 1、Spring配置文件 beans.xml 引用一个具体的值(value):
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring这些都称之为Bean
类型 变量名=new 类型();
Hello hello=new Hello();
bean=对象 new Hello()
id=变量名
class=new 的对象:
property 相当于给对象中的属性设置一个值
-->
<bean id="hello" class="com.ma.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
- 2、Spring配置文件 beans.xml 引用Spring容器中创建好的对象(ref):
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="impl" class="com.ma.dao.UserDaoImpl"/>
<bean id="mySqlImpl" class="com.ma.dao.UserDaoMysqlImpl"/>
<bean id="userServiceImpl" class="com.ma.service.UserServiceImpl">
<!--
ref 引用Spring容器中创建好的对象
value : 具体的值:基本数据类型
-->
<property name="userDao" ref="mySqlImpl"/>
</bean>
</beans>
- 测试类MyTest:
public class MyTest {
public static void main(String[] args) {
// 获取Spring 的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 我们的对象现在都在Spring中管理了,我们要使用 直接去里面取出来就可以了
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
5. IOC创建对象的方式:
-
默认使用无参构造创建对象。
-
假设我们要使用有参构造创建对象。
- 参数下标赋值:
<!--有参构造创建对象,通过下标赋值-->
<bean id="user" class="com.ma.pojo.User">
<constructor-arg index="0" value="小马同学"/>
</bean>
- 参数类型赋值,不建议使用(若两个参数类型相同):
<!--有参构造创建对象,通过类型赋值-->
<bean id="user" class="com.ma.pojo.User">
<constructor-arg type="java.lang.String" value="小马呀"/>
</bean>
- 直接通过参数名来设置
<!--第三种,直接通过参数名来设置-->
<bean id="user" class="com.ma.pojo.User">
<constructor-arg name="name" value="小马哈哈"/>
</bean>
- 当加载SpringBean配置文件的时候,容器中管理的对象就已经初始化了
如:再创建一个实体类UserT
public class UserT {
public UserT() {
System.out.println("UserT创建了");
}
}
在beans.xml中注册:
<bean id="userT" class="com.ma.pojo.UserT">
</bean>
当加载beans.xml时,控制台就打印出:UserT创建了
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
6. Spring 配置:
6.1、别名:
- 使用alias标签
<!--别名,如果添加了别名,我们也可以通过别名获取到这个对象-->
<alias name="user" alias="aaaaa"/>
- 使用bean标签中的name属性(可以赋多个别名)
<bean id="userT" class="com.ma.pojo.UserT" name="t,m"></bean>
6.2、Bean的配置:
<!--
id: bean的唯一标识符 也就是相当于我们学的对象名
class:bean对象所对应的权限定名:包名+类名
name:也是别名,而且name可以同时取多个别名
-->
<bean id="userT" class="com.ma.pojo.UserT" name="t,m" ></bean>
6.3、import导入:
这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,这时候,我们就可以利用import将所有人的beans.xml合并为一个总的,使用的时候,直接使用总的就可以了
- 小马
- 小赵
- 小李
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
</beans>
7. DI依赖注入:
7.1、构造器注入:
前面已经写过,见上面 5. IOC创建对象的方式
7.2、Set方式注入【重点】:
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
- 复杂类型:Address类:
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
- 真实测试对象:Student类
public class Student {
private String name;
private Address address;
private String[]books;
private List<String>hobbies;
private Map<String,String>card;
private Set<String>games;
private String wife;
private Properties info;
...
get,set
...
}
- beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.ma.pojo.Address">
<property name="address" value="南京"/>
</bean>
<bean id="student" class="com.ma.pojo.Student">
<!--第一种:普通值注入:value-->
<property name="name" value="小马同学"/>
<!--第二种:对象注入:ref-->
<property name="address" ref="address"/>
<!--第三种:数组注入: 通过array和value标签-->
<property name="books" >
<array>
<value>七龙珠</value>
<value>海贼王</value>
<value>火影忍者</value>
</array>
</property>
<!--第四种:List集合注入:通过list和value标签-->
<property name="hobbies">
<list>
<value>敲代码</value>
<value>听歌</value>
<value>跑步</value>
</list>
</property>
<!--第五种:Map集合注入:map和entry标签-->
<property name="card">
<map>
<entry key="身份证" value="32342219540223453X"/>
<entry key="手机号码" value="13309234287"/>
</map>
</property>
<!--第六种:set集合注入:set和value标签-->
<property name="games">
<set>
<value>英雄联盟</value>
<value>刺激战场</value>
<value>王者荣耀</value>
</set>
</property>
<!--第七种:null注入:null标签-->
<property name="wife">
<null/>
</property>
<!--第八种 Properties配置文件注入-->
<property name="info">
<props>
<prop key="driver">com.ma.he</prop>
<prop key="url">www.baidu.com</prop>
<prop key="username">root</prop>
<prop key="password">111111</prop>
</props>
</property>
</bean>
</beans>
- 测试类:MyTest
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
- 打印结果:
Student{name='小马同学', address=Address{address='南京'}, books=[七龙珠, 海贼王, 火影忍者], hobbies=[敲代码, 听歌, 跑步], card={身份证=32342219540223453X, 手机号码=13309234287}, games=[英雄联盟, 刺激战场, 王者荣耀], wife='null', info={password=111111, url=www.baidu.com, driver=com.ma.he, username=root}}
7.3、拓展方式:
官方文档:
- p-命名空间:
在配置文件的头部beans标签里加入:xmlns:p=“http://www.springframework.org/schema/p”
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.ma.pojo.User" p:name="小马" p:age="23"/>
</beans>
- c-命名空间:
在配置文件的头部beans标签里加入:xmlns:c=“http://www.springframework.org/schema/c”
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.ma.pojo.User" c:name="小马同学" c:age="18"/>
</beans>
- 测试:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user",User.class);
User user2 = context.getBean("user2",User.class);
System.out.println(user);
System.out.println(user2);
}
// 输出:User{name='小马', age=23}
// User{name='小马同学', age=18}
注意:p命名和c命名空间不能直接使用,需要导入xml约束。
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
7.4、Bean的作用域:
- 单例模式【Spring的默认机制】 scope=singleton
<bean id="user2" class="com.ma.pojo.User" c:name="小马同学" c:age="18" scope="singleton"/>
- 原型模式:每次从容器get的时候,都会产生一个新的对象 scope=“prototype”
<bean id="user2" class="com.ma.pojo.User" c:name="小马同学" c:age="18" scope="prototype"/>
- 其余的request、Session、application,这些只能在web开发中使用到。
8. Bean的自动装配:
- 自动装配是Spring满足bean依赖一种方式
- Spring 会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种自动装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean【重要】
8.1、测试:
- 环境搭建:一个人有两个宠物
- Cat类:
public class Cat {
public void shout(){
System.out.println("喵~");
}
}
- Dog类:
public class Dog {
public void shout(){
System.out.println("汪~");
}
}
- People类:
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
8.2、ByName自动装配:
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanId
-->
<bean id="people" class="com.ma.pojo.People" autowire="byName">
<property name="name" value="小马呀"/>
</bean>
8.3、ByType自动装配:
<!-- byType:会自动在容器上下文中查找,和自己对象属性类型对应的bean-->
<bean id="people" class="com.ma.pojo.People" autowire="byType">
<property name="name" value="小马呀"/>
</bean>
小结:
- 在byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
- 在bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
8.4、使用注解实现自动装配:
jdk1.5支持注解,Spring2.5就支持注解了
要使用注解需知:
- 导入约束:context约束
- 配置注解的支持(全部配置如下):
<context:annotation-config/>
【重要】
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
1.@Autowired:
直接在属性上使用即可,也可以在set方式上使用!
使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在。且符合属性byType
科普:
@Nullable // 字段标记了这个注解,说明这个字段可以为null
public @interface Autowired {
boolean required() default true;
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”) 去配合@Autowired的使用,指定一个唯一的bean对象注入。
public class People {
// 如果显示定义了Autowired的required属性为false,说明如果找不到装配的 不抛出异常
@Autowired
@Qualifier(value = "cat1")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
private String name;
}
2. @Resource注解:
public class People {
@Resource(name = "cat1")
private Cat cat;
@Resource
private Dog dog;
private String name;
}
小结:
@Resource和@Autowired的区别:
- 都是用来自动装配,都可以放在属性字段上
- @Autowired默认是byType装配的
- @Resource默认通过byName方式实现,如果找不到名字,则通过byType实现!如果两个都找不到就报错
9. 使用注解开发:
在Spring4之后,要使用注解开发,必须保证 aop的包导入了
使用注解需要导入context约束,增加注解的支持、
1. @Component:
- @Component:组件,放在类上,说明这个类被Spring管理bean ,
同时要在配置文件applicationConetxt.xml中申明指定要扫描的包,这个包下的注解就会生效
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.ma.pojo"/>
等价于:
<bean id="user" class="com.ma.pojo.User"/>
-
衍生的注解:
@Component有几个衍生的注解,我们在web开发中,会按照MVC三层架构
- dao :【@Repository】
- service :【@Service】
- controller:【@Controller】
这四个注解功能是一样的,都是代表将某个类注册到Spring中,装配Bean
2. @Value:
@Value:给属性赋值,加在属性或set方法上面,相当于:
<property name="name" value="小马"/>
如:
@Component
public class User {
@Value("小马")
public String name;
}
3. @Scope作用域注解:
@Component
@Scope("singleton")
public class User {
@Value("小马")
public String name;
}
4. 测试:
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 对象名为类的小写
User user = context.getBean("user", User.class);
System.out.println(user.name);
}
}
小结:xml和注解
- xml更加的万能,适用于任何场合,维护简单方便
- 注解不是自己的类使用不了,维护较为复杂
- 最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入
- 我们在使用的过程中,只需要注意一个问题:想让注解生效,就必须开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.ma"/>
<context:annotation-config></context:annotation-config>
10. 使用javaConfig实现配置:
我们现在要完全不使用Spring的xml配置了,全权交给java来做。
JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能
- 实体类User:
// 这里这个注解的意思,就是说明这个类被Spring接管了,注册到容器中
@Component
public class User {
@Value("小马") // 属性注入值
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
- 配置类MyConfig:
/ 这个也会被Spring容器托管,注册到容器中,他本身也是个@Component
// @Configuration 代表这是一个配置类,就和我们之前的beans.xml一样
@Configuration
@ComponentScan("com.ma.pojo")
@Import(MyConfig2.class) // 合并配置类
public class MyConfig {
// 注册一个bean,就相当于我们之前写的一个bean标签
// 这个方法中的名字,就相当于bean标签的id属性
// 这个方法的返回值,就相当于bean标签的class属性
@Bean
public User getUser(){
return new User(); // 就是返回要注入到bean的对象
}
}
- 测试类MyTest:
public class MyTest {
@Test
public void getUser(){
// 如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfigApplicationContext来获取容器,
// 通过配置类的class对象加载
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("getUser");
System.out.println(user.getName());
}
}
这种纯java的配置方式,在SpringBoot中随处可见
10. 代理模式:
因为这就是SpringAOP的底层【SpringAOP 和 SpringMVC】
代理模式的分类:
-
静态代理
-
动态代理
10.1、静态代理:
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色 房东
- 代理角色:代理真实角色,代理真实角色后,一般会做一些附属操作 中介
- 客户:访问代理对象的人 租房的人
- 租房接口House:
// 租房接口
public interface House {
public void rent();
}
- 房东要租房子HouseOwner:
// 房东
public class HouseOwner implements House{
public void rent() {
System.out.println("房东出租房子");
}
}
- 中介帮房东代理Proxy:
public class Proxy implements House {
private HouseOwner hostOwner;
public Proxy(HostOwner hostOwner) {
this.hostOwner = host;
}
public Proxy() {
}
public void rent() {
seeHouse();
hetong();
host.rent();
fare();
}
// 看房
public void seeHouse(){
System.out.println("中介带你看房");
}
// 签合同
public void hetong(){
System.out.println("签租赁合同");
}
// 收中介费
public void fare(){
System.out.println("中介收中介费");
}
}
- 我去租房子Client:
public class Client {
public static void main(String[] args) {
// 房东要租房子
HostOwner hostOwner = new HostOwner();
// 代理,中介帮房东租房子,但是,中介会有一些附属操作
Proxy proxy = new Proxy(hostOwner);
// 你不用面对房东,直接找中介租房即可
proxy.rent();
}
}
代理模式的好处:
- 可以使真实角色的操作更加纯粹,不用去关注其他公共业务
- 公共业务就交给代理角色,实现了业务的分工。
- 公共业务发生扩展的时候,方便集中管理
缺点:
- 一个真实角色就需要一个代理角色,代码量会翻倍,开发效率低
10.2、静态代理再理解:
- UserService类:
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
- UserServiceImp实现类:
// 真实对象
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加一个用户");
}
public void delete() {
System.out.println("删除一个用户");
}
public void update() {
System.out.println("更新一个用户");
}
public void query() {
System.out.println("查询一个用户");
}
}
- UserServiceProxy代理类:
public class UserServiceProxy implements UserService{
UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
// 日志方法
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
- 调用类Client:
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy userServiceProxy = new UserServiceProxy();
userServiceProxy.setUserService(userService);
userServiceProxy.add();
}
}
10.3、动态代理:
- 动态代理和静态代理的角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的。
- 动态代理主要分为两大类,基于接口的动态代理,基于类的动态代理
- 基于接口—>JDK的动态代理 [我们在这里实现]
- 基于类的—>cglib
- java字节码实现:javassist
需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序
InvocationHandle:
案列:
- 一个房屋接口House:
public interface House {
public void rent();
}
- 房东需要出租房子HouseOwner:
public class HouseOwner implements House {
public void rent() {
System.out.println("房东出租房子");
}
}
- 自动生成代理类ProxyInvocationHandler:
// 自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理的接口
private House house;
public void setHouse(House house) {
this.house = house;
}
// 生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), house.getClass().getInterfaces(), this);
}
// 处理代理类实例 调用方法 并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
Object result = method.invoke(house, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介看房子");
}
public void fare(){
System.out.println("收中介费");
}
}
- 租房子测试Client:
public class Client {
public static void main(String[] args) {
HouseOwner houseOwner=new HouseOwner();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
// 设置要代理的对象
pih.setHouse(houseOwner);
// 代理角色
House proxy = (House) pih.getProxy(); // 这里的proxy 就是通过Proxy.newProxyInstance()动态生成的
proxy.rent(); // 调用的是invoke()方法
}
}
// 执行结果:
// 中介看房子
// 房东出租房子
// 收中介费
- 整合ProxyInvocationHandler,可为任何接口创建代理类:
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
// 动态的生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
// 处理代理类实例 调用方法 并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// log(method.getName());
Object result = method.invoke(target, args);
return result;
}
// 添加一个额外的方法
/* public void log(String msg){
System.out.println("执行了"+msg+"方法");
}*/
}
测试类:
public class Client {
public static void main(String[] args) {
// 真实角色
UserServiceImpl userService=new UserServiceImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
// 设置要代理的对象
pih.setTarget(userService);
// 代理角色
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}
10.4、总结:
动态代理的好处:
- 可以使真实角色的操作更加纯粹,不用去关注其他公共业务
- 公共业务就交给代理角色,实现了业务的分工。
- 公共业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的接口,一般就是对应的一类业务。
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可。
11. AOP:
11.1、什么是AOP:
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP在Spring中的作用:
提供声明式事务;允许用户自定义切面
以下名词需要了解下:
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
- 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YhRBScVo-1628057368903)(C:\Users\user\Desktop\java分析图\66Spring中AOP.png)]
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
11.3、使用Spring实现AOP
【重点】使用AOP织入,需要导入一个依赖包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一: 使用Spring的API接口:
切点–>执行
<aop:config>
<!--切入点: expression:表达式 execution(要执行的位置 * * * * * )-->
<aop:pointcut id="pointcut" expression="execution(* com.ma.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="BeforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
</aop:config>
如:
- UserService接口:
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
- UserServiceImpl实现类:
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
- 方法执行前日志BeforeLog:
// 方法执行前
public class BeforeLog implements MethodBeforeAdvice {
// method:要执行的目标对象的方法
// args : 参数
// target : 目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
- 返回结果后日志AfterLog:
// 返回结果后
public class AfterLog implements AfterReturningAdvice {
// returnValue :返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"返回结果为:"+returnValue);
}
}
- 配置文件applicationContext.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--注册bean-->
<bean id="userService" class="com.ma.service.UserServiceImpl"/>
<bean id="BeforeLog" class="com.ma.log.BeforeLog"/>
<bean id="AfterLog" class="com.ma.log.AfterLog"/>
<!--方式一:使用原生的Spring API接口 -->
<!--配置aop: 需要导入AOP的约束-->
<aop:config>
<!--切入点: expression:表达式 execution(要执行的位置 * * * * * )-->
<aop:pointcut id="pointcut" expression="execution(* com.ma.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="BeforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="AfterLog" pointcut-ref="pointcut"/>
</aop:config>
- 测试类MyTest:
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 动态代理,代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
// 执行结果
// com.ma.service.UserServiceImpl的add被执行了
// 增加了一个用户
// 执行了add返回结果为:null
方式二:自定义来实现AOP:
切面(被模块化的对象)–>切点–>通知
<aop:config>
<!--自定义切面,ref 要引用类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.ma.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
如:
- 定义的切面diyPointCut:
public class diyPointCut {
public void before(){
System.out.println("=====方法执行前=====");
}
public void after(){
System.out.println("=====方法执行后=====");
}
}
- 配置applicationContext.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--注册bean-->
<bean id="userService" class="com.ma.service.UserServiceImpl"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.ma.diy.diyPointCut"/>
<aop:config>
<!--自定义切面,ref 要引用类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.ma.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
方式三:注解
- 定义一个切面类AnnotationPointCut:
@Component
@ComponentScan
@Aspect // 标注这个面是一个切面
public class AnnotationPointCut {
@Before("execution(* com.ma.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---方法执行前---");
}
@After("execution(* com.ma.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---方法执行后---");
}
// 在环绕增强中,我们可以给定一个参数,代表我们要获取处理的切入点
@Around("execution(* com.ma.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("---环绕前---");
Signature signature = jp.getSignature(); // 获得签名
System.out.println(signature); // void com.ma.service.UserService.add()
// 执行方法
Object proceed = jp.proceed();
System.out.println("---环绕后---");
}
}
- 在applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注册bean-->
<bean id="userService" class="com.ma.service.UserServiceImpl"/>
<bean id="BeforeLog" class="com.ma.log.BeforeLog"/>
<bean id="AfterLog" class="com.ma.log.AfterLog"/>
<!--方式三-->
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.ma.diy"/>
<!--开启注解支持
JDK 基于接口(默认 proxy-target-class="false")
cglib 基于类(proxy-target-class="true")
-->
<aop:aspectj-autoproxy />
</beans>
- 测试结果:
---环绕前---
void com.ma.service.UserService.add()
---方法执行前---
增加了一个用户
---环绕后---
---方法执行后---
12. 整合MyBatis:
步骤:
- 导入相关的jar包
- junit
- mybatis
- mysql数据库
- spring相关的
- aop织入
- mybatis-spring 【新的】
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--Spring 操作数据库的话 还需要一个spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
- 编写配置文件
- 测试
12.1、Mybatis-spring:
方式一:SqlSessionTemplate
- 编写实体类User:
@Data
public class User {
private int id;
private String name;
private String pwd;
}
- 编写UserMapper接口:
public interface UserMapper {
public List<User> selectUser();
}
- 编写数据库执行语句UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ma.mapper.UserMapper">
<select id="selectUser" resultType="com.ma.pojo.User">
select * from mybatis.user
</select>
</mapper>
- MyBatis配置文件mybatis-config.xml:
<?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>
<typeAliases>
<package name="com.ma.pojo"/>
</typeAliases>
<!--设置-->
<!-- <settings>
<setting name="" value=""/>
</settings>-->
</configuration>
- spring和mybatis结合的配置文件spring-dao.xml (通用,主要用来配置mybatis): dataSource–>sqlSessionFactory–>SqlSessionTemplate
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--DataSource: 使用Spring的数据源替换mybatis的配置
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="087415157"/>
</bean>
<!--sqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/ma/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate 就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能用构造器注入sqlSessionFactory 他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
- 创建一个UserMapper实现类UserMapperImpl,执行方法:
public class UserMapperImpl implements UserMapper {
// 我们的所有操作,在原来使用sqlSession来执行,现在都使用sqlSessionTemplate;
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
- 创建一个applicationContext.xml,用来注册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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="spring-dao.xml"/>
<!---->
<bean id="userMapper" class="com.ma.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
- 测试:
public class MyTest {
@Test
public void test() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
方式二:SqlSessionDaoSupport:
改动的地方:
- UseServiceImp:
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
- 删除spring-dao.xml中SqlSessionTemplated的注入
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--DataSource: 使用Spring的数据源替换mybatis的配置
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="087415157"/>
</bean>
<!--sqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/ma/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate 就是我们使用的sqlSession-->
<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!–只能用构造器注入sqlSessionFactory 他没有set方法–>
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>-->
</beans>
- 修改applicationContext.xml文件,直接映射sqlSessionFactory:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="spring-dao.xml"/>
<!---->
<!-- <bean id="userMapper" class="com.ma.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>-->
<bean id="userMapper" class="com.ma.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
13. 声明事务:
13.1、回顾事务:
- 把一组业务当做一个业务来做,要么都成功,要么都失败
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务的ACID原则:
- 原子性
- 一致性
- 隔离性
- 持久性
13.2、spring中的事务管理:
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理
事务的传播机制:
事务的传播性一般用在事务嵌套的场景,比如一个事务方法里面调用了另外一个事务方法,那么两个方法是各自作为独立的方法提交还是内层的事务合并到外层的事务一起提交,这就是需要事务传播机制的配置来确定怎么样执行。
常用的事务传播机制如下:
- PROPAGATION_REQUIRED(propagation_required)
Spring默认的传播机制,能满足绝大部分业务需求,如果外层有事务,则当前事务加入到外层事务,一块提交,一块回滚。如果外层没有事务,新建一个事务执行 - PROPAGATION_REQUES_NEW(propagation_reques_new)
该事务传播机制是每次都会新开启一个事务,同时把外层事务挂起,当当前事务执行完毕,恢复上层事务的执行。如果外层没有事务,执行当前新开启的事务即可 - PROPAGATION_SUPPORT (propagation_support)
如果外层有事务,则加入外层事务,如果外层没有事务,则直接使用非事务方式执行。完全依赖外层的事务 - PROPAGATION_NOT_SUPPORT (propagation_not_support)
该传播机制不支持事务,如果外层存在事务则挂起,执行完当前代码,则恢复外层事务,无论是否异常都不会回滚当前的代码 - PROPAGATION_NEVER (propagation_never)
该传播机制不支持外层事务,即如果外层有事务就抛出异常 - PROPAGATION_MANDATORY (propagation_mandatory)
与NEVER相反,如果外层没有事务,则抛出异常 - PROPAGATION_NESTED (propagation_nested)
该传播机制的特点是可以保存状态保存点,当前事务回滚到某一个点,从而避免所有的嵌套事务都回滚,即各自回滚各自的,如果子事务没有把异常吃掉,基本还是会引起全部回滚的。
传播规则回答了这样一个问题:一个新的事务应该被启动还是被挂起,或者是一个方法是否应该在事务性上下文中运行。
事务的隔离级别:
事务的隔离级别定义一个事务可能受其他并发务活动活动影响的程度,可以把事务的隔离级别想象为这个事务对于事物处理数据的自私程度。
在一个典型的应用程序中,多个事务同时运行,经常会为了完成他们的工作而操作同一个数据。并发虽然是必需的,但是会导致以下问题:
- 脏读(Dirty read)
脏读发生在一个事务读取了被另一个事务改写但尚未提交的数据时。如果这些改变在稍后被回滚了,那么第一个事务读取的数据就会是无效的。 - 不可重复读(Nonrepeatable read)
不可重复读发生在一个事务执行相同的查询两次或两次以上,但每次查询结果都不相同时。这通常是由于另一个并发事务在两次查询之间更新了数据。
不可重复读重点在修改。
- 幻读(Phantom reads)
幻读和不可重复读相似。当一个事务(T1)读取几行记录后,另一个并发事务(T2)插入了一些记录时,幻读就发生了。在后来的查询中,第一个事务(T1)就会发现一些原来没有的额外记录。
幻读重点在新增或删除。
在理想状态下,事务之间将完全隔离,从而可以防止这些问题发生。然而,完全隔离会影响性能,因为隔离经常涉及到锁定在数据库中的记录(甚至有时是锁表)。完全隔离要求事务相互等待来完成工作,会阻碍并发。因此,可以根据业务场景选择不同的隔离级别。
repeatable
隔离级别 | 含义 |
---|---|
ISOLATION_DEFAULT | 使用后端数据库默认的隔离级别 |
ISOLATION_READ_UNCOMMITTED | 允许读取尚未提交的更改。可能导致脏读、幻读或不可重复读。 |
ISOLATION_READ_COMMITTED | (Oracle 默认级别)允许从已经提交的并发事务读取。可防止脏读,但幻读和不可重复读仍可能会发生。 |
ISOLATION_REPEATABLE_READ | (MYSQL默认级别)对相同字段的多次读取的结果是一致的,除非数据被当前事务本身改变。可防止脏读和不可重复读,但幻读仍可能发生。 |
ISOLATION_SERIALIZABLE | 完全服从ACID的隔离级别,确保不发生脏读、不可重复读和幻影读。这在所有隔离级别中也是最慢的,因为它通常是通过完全锁定当前事务所涉及的数据表来完成的。 |
只读
如果一个事务只对数据库执行读操作,那么该数据库就可能利用那个事务的只读特性,采取某些优化措施。通过把一个事务声明为只读,可以给后端数据库一个机会来应用那些它认为合适的优化措施。由于只读的优化措施是在一个事务启动时由后端数据库实施的, 因此,只有对于那些具有可能启动一个新事务的传播行为(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、 ROPAGATION_NESTED)的方法来说,将事务声明为只读才有意义。
事务超时
为了使一个应用程序很好地执行,它的事务不能运行太长时间。因此,声明式事务的下一个特性就是它的超时。
假设事务的运行时间变得格外的长,由于事务可能涉及对数据库的锁定,所以长时间运行的事务会不必要地占用数据库资源。这时就可以声明一个事务在特定秒数后自动回滚,不必等它自己结束。
由于超时时钟在一个事务启动的时候开始的,因此,只有对于那些具有可能启动一个新事务的传播行为(PROPAGATION_REQUIRES_NEW、PROPAGATION_REQUIRED、ROPAGATION_NESTED)的方法来说,声明事务超时才有意义。
回滚规则
在默认设置下,事务只在出现运行时异常(runtime exception)时回滚,而在出现受检查异常(checked exception)时不回滚(这一行为和EJB中的回滚行为是一致的)。
不过,可以声明在出现特定受检查异常时像运行时异常一样回滚。同样,也可以声明一个事务在出现特定的异常时不回滚,即使特定的异常是运行时异常。
在spring-dao.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--DataSource: 使用Spring的数据源替换mybatis的配置
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="087415157"/>
</bean>
<!--sqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/ma/dao/*.xml"/>
</bean>
<!--SqlSessionTemplate 就是我们使用的sqlSession-->
<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!–只能用构造器注入sqlSessionFactory 他没有set方法–>
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>-->
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性,新-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.ma.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
spring声明式事务参考
事物配置中有哪些属性可以配置?以下只是简单的使用参考
- 事务的传播性:
@Transactional(propagation=Propagation.REQUIRED) - 事务的隔离级别:
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
读取未提交数据(会出现脏读, 不可重复读) 基本不使用
- 只读:
@Transactional(readOnly=true)
该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。 - 事务的超时性:
@Transactional(timeout=30) - 回滚:
指定单一异常类:@Transactional(rollbackFor=RuntimeException.class)
指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class})
该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。
思考:
为什么需要事务
-
如果不配置事务,可能存在数据提交不一致的情况
-
如果我们不在spring中去配置声明事务,我们就需要在代码中手动配置事务
-
事务在项目的开发中十分重要,设计到数据的一致性和完整性问题
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="087415157"/>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性,新-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.ma.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
```
spring声明式事务参考
事物配置中有哪些属性可以配置?以下只是简单的使用参考
- 事务的传播性:
@Transactional(propagation=Propagation.REQUIRED) - 事务的隔离级别:
@Transactional(isolation = Isolation.READ_UNCOMMITTED)
读取未提交数据(会出现脏读, 不可重复读) 基本不使用
- 只读:
@Transactional(readOnly=true)
该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。 - 事务的超时性:
@Transactional(timeout=30) - 回滚:
指定单一异常类:@Transactional(rollbackFor=RuntimeException.class)
指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class})
该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。
思考:
为什么需要事务
- 如果不配置事务,可能存在数据提交不一致的情况
- 如果我们不在spring中去配置声明事务,我们就需要在代码中手动配置事务
- 事务在项目的开发中十分重要,设计到数据的一致性和完整性问题