Spring介绍
- Spring是致力于解决企业级开发软件的各层技术。
- Spring相当于一个技术大杂烩,将各种技术方案整合在一起。
- 2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
- 2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版本。
- 很难想象Rod Johnson的学历,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
- Spring理念:使现有的技术更加实用,spring本身就是一个大杂烩,整合现有的框架技术。
- 官网:https://spring.io/
- 官方下载地址:https://repo.spring.io/libs-release-local/org/springframework/spring/
- GitHub : https://github.com/spring-projects
Spring的优势
-
Spring是一个开源的轻量级、非侵入式的框架
-
控制反转loC,面向切面Aop
-
对事物的支持 , 对框架的支持
一句话概括:
Spring是一个轻量级的控制反转(loC)和面向切面(AoP)的容器(框架)
Spring的组成
Spring由七大部分组成,Aop、core、SpringMvc、ORM、Web、Context,他们是相互独立,也可以在一起使用。
Core:核心容器,提供Spring框架的基本功能。核心容器的主要组件是BeanFactory,他是工厂模式的
的实现。BeanFactory使用控制反转(lOC)模式将应用程序的配置和依赖性规范与实际应用程序代码
分开。
Context:Spring的上下文是一个配置文件,向Spring框架提供上下文信息。
Spring上下文包括企业服务,例如:JNDl、EJB、电子邮件、国际化、效验
和调度功能。
Spring AOP:通过配置管理功能,Spring AOP模块直接将面向切面的编程功能,
集成到了Spring框架中。所以,可以很容易的使Spring框架管理任何支持AOP
的对象。Spring AOP 模块为基于Spring的应用程序中的对象提供了事务管理
功能。通过使用Spring AOP,不用依赖组件,就可以将声明性事物管理集成到
应用程序中。
Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理
异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且
极大地降低了需要编写的异常代码的数量(例如打开和关闭连接)。Spring DAO 面向
JDBC 的异常,是遵从通用的 DAO 异常层次结构。
Spring ORM:Spring 框架插入了若干个ORM框架,从而提供了ORM的对象关系工具,
其中包括了JDO 、HIbernate和iBtais SQL Map。所有这些都遵从 Spring的通用事物
和 DAO 异常层次结构。
Spring Web 模块:Web上下文模块建立在应用程序上下文模块之上,为基于Web的应用程序
提供了上下文。所以Spring 框架支持与Jakarta Struts 的集成。Web 模块还简化了处理
多部分请求和以及请求参数绑定到域对象的工作。
Spring MVC 框架:MVC框架是一个全功能的构架Web 应用程序的MVC 实现。通过策略
接口,MVC 框架变成为高度可配置的容器,MVC容纳了大量视图技术,其中包括JSP、Velocity、
Tiles、iText和POl。
Sping Boot 与 Spring Clound
- Spring Boot 是 Spring 的一套快速配置脚手架,可以基于Spring Boot 快速开发单个微服务;
- Spring Cloud是基于Spring Boot实现的;
- Spring Boot专注于快速、方便集成的单个微服务个体,Spring Cloud关注全局的服务治理框架;
- Spring Boot使用了约束优于配置的理念,很多集成方案已经帮你选择好了,能不配置就不配置 , Spring Cloud很大的一部分是基于Spring Boot来实现,Spring Boot可以离开Spring Cloud独立使用开发项目,但是Spring Cloud离不开Spring Boot,属于依赖的关系。
- SpringBoot在SpringClound中起到了承上启下的作用,如果你要学习SpringCloud必须要学习SpringBoot。
图解:
IOC介绍
IOC介绍
控制反转lOC(lnversion of Control),是一种设计思想,Dl(依赖注入)是实现loc的一种方法,也有人认为Dl只是loC的
另一种说法。没有loc的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象
的创建由程序控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。简单说来就是将类集中在Spring中,由Spring进行管理。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vFkCpOvF-1615946896309)(E:\自学笔记\狂神说Java\Spring框架\image\程序耦合图解.png)]
IoC是Spring框架的核心内容,使用多种方式完美的实现了IoC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现IoC。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从Ioc容器中取出需要的对象。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lj8ZAM2S-1615946896310)(E:\自学笔记\狂神说Java\Spring框架\image\Spring程序的执行步骤.png)]
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。
创建一个Spring项目
IDEA中Spring项目,有两种创建方式:第一种是创建Maven工程,通过导入jar,自行下载。
第二种就是直接新建项目,选择Spring进行创建。
<!--我们使用Spring MVC的Jar,他会自动将其他Spring的jar下载好-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<!-- JDBC的jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
我们以Maven工程为例,创建一个空Maven工程
第一个Spring程序
//学生接口
public interface StudentDao {
void run();
}
//学生接口实现类2
public class StudentDao2Impl implements StudentDao {
@Override
public void run() {
System.out.println("我在学习");
}
}
//学生接口实现类1
public class StudentDaoImpl implements StudentDao {
@Override
public void run() {
System.out.println("我在吃饭");
}
}
//控制类
public class ServiceDao {
private StudentDao studentDao;
//构造方法
public ServiceDao() {}
public ServiceDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
//get、set的方法
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
//Spring的应用(创建对象) 测试类
public class Test {
//传统创建对象的方式
public static void test() {
//创建控制类
ServiceDao serviceDao = new ServiceDao();
//设置对象属性
serviceDao.setStudentDao(new StudentDaoImpl());
//调用方法
serviceDao.getStudentDao().run();
}
//使用Spring进行创建对象
public static void test2() {
//加载Xml文件
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
//获取对象
ServiceDao serviceDao = (ServiceDao) ac.getBean("studentService");
//调用方法
serviceDao.getStudentDao().run();
}
public static void main(String[] args) {
//测试结果
test();
test2();
}
}
Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd" >
<!-- 使用Spring来对类进行统一的管理 -->
<!-- bean是Spring创建对象的标签,id 表示对象名称 class表示类的位置-->
<bean id="student" class="com.njxh.dao.imp.StudentDaoImpl"></bean>
<bean id="student2" class="com.njxh.dao.imp.StudentDao2Impl"></bean>
<bean id="studentService" class="com.njxh.service.ServiceDao">
<!-- property 给对象设置属性值 name 属性的名称 ref 引用别的对象
注意:如果类的属性不是一个对象,而是基本类型属性的话,使用value进行赋值
-->
<property name="studentDao" ref="student2"></property>
<!--
<property name="name" value="你好"></property>
-->
</bean>
</beans>
我们来思考两个问题?
1、使用Spring对类进行统一管理,对象是谁创建的?
是Spring创建的
2、对象的属性是谁设置的?
是Spring设置的
这个过程就叫控制反转 :
- 控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring后 , 对象是由Spring来创建的
- 反转 : 程序本身不创建对象 , 而变成被动的接收对象 .
依赖注入:通过set方法(给对象属性赋值)
IOC是一种编程思想,由主动的编程变成被动的接收
可以通过newClassPathXmlApplicationContext去浏览一下底层源码
IOC对象创建的方式
//狗类
public class Dao {
private String name;
public Dao() {
System.out.println("初始化Dao");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//猫类
public class Car {
private String name;
public Car() {
System.out.println("初始化Car");
}
public Car(String name) {
this.name = name;
System.out.println("初始化Car");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//测试类
public class Test {
public static void main(String[] args) {
//加载xml
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
//获取对象
Dao dao = (Dao)ac.getBean("dao");
System.out.println(dao);
}
}
Spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd" >
<!-- IOC对象创建的方式 -->
<bean id="dao" class="com.njxh.bean.Dao">
<!-- 通过无参构造方法创建对象 -->
<property name="name" value="小狗"></property>
</bean>
<bean id="car" class="com.njxh.bean.Car">
<!-- 通过有参构造方法创建对象 一共有三中方式-->
<!-- 第一种:通过参数的名称-->
<constructor-arg name="name" value="小猫"></constructor-arg>
<!--
第二种:通过index索引
<constructor-arg index="0" value="小猫"></constructor-arg>
第三种:通过数据类型
<constructor-arg type="java.lang.String" value="小猫"></constructor-arg>
-->
</bean>
<!--
注意:
1、如果类没有构造方法,默认是用无参构造方法创建对象
2、如果类有有参构造方法,没有无参构造方法,定义bean,必须使用有
参构造方法赋值参数,否则报错
3、如果类中既有无参也有有参构造方法,定义bean时,任意选择
-->
</beans>
运行结果:
我们之前讲过,Spring在初始化时,会先加载配置文件,创建相应的对象放入容器中。
我们在用到时,在通过IOC进行获取
Spring配置
别名
alias name 对象名 alias 别名
<alias name="dao" alias="dao2"></alias>
Bean的配置
bean就是Java对象,由Spring创建和管理
id 是bean的唯一标识,如果没有配置name就是默认标识符
如果配置id,有配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象
class 是bean的全限定名=包名+类名
<bean id="dao" name="dao2 dao3,dao4:dao5" class="com.njxh.bean.Dao">
<property name="name" value="小狗"></property>
</bean>
import
import可以将一个项目中多个Spring的配置文件,导入一个xml文件中
<import resource="{path}/beans.xml" />
依赖注入
概念
- 依赖注入(Dependency Injection,DI)
- 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
- 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .
bean对象:属性、集合、null注入、p、c命名空间注入
//Dog类
public class Dog {
private String name;
public Dog() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
//人类
public class People {
private String name;
private Dog dog;
private String[] arry;
private List list;
private Map map;
private Set set;
private Properties properties;
public People() {}
public People(String name,List list) {
this.name = name;
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setArry(String[] arry) {
this.arry = arry;
}
public List getList() {
return list;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Map getMap() {
return map;
}
public void setList(List list) {
this.list = list;
}
public Set getSet() {
return set;
}
public void setMap(Map map) {
this.map = map;
}
public String[] getArry() {
return arry;
}
public void setSet(Set set) {
this.set = set;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", dog=" + dog +
", arry=" + Arrays.toString(arry) +
", list=" + list +
", map=" + map +
", set=" + set +
", properties=" + properties +
'}';
}
}
//测试
public class Test {
private ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//依赖注入
@org.junit.Test
public void test() {
//获取对象
People people = context.getBean("people",People.class);
//打印数据
System.out.println(people);
}
//p、c命名空间注入
@org.junit.Test
public void test2() {
//p命名空间注入
People people = context.getBean("people2",People.class);
//打印数据
System.out.println(people + "\n");
//c命名空间注入
People people1 = context.getBean("people3",People.class);
//打印数据
System.out.println(people1);
}
}
# 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:p="http://www.springframework.org/schema/p"
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" >
<!-- 基本类型、集合、对象注入 -->
<bean id="dog" class="com.njxh.bean.Dog"></bean>
<bean id="people" class="com.njxh.bean.People">
<!-- 基本类型 -->
<property name="name" value="小王"></property>
<!-- 对象引用和内部bean -->
<!-- <property name="dog" ref="dog"></property>-->
<property name="dog">
<bean class="com.njxh.bean.Dog"></bean>
</property>
<!-- 数组引用 -->
<property name="arry">
<array>
<value>你好,我是</value>
<value>我是</value>
<value>你们的</value>
<value>新同学</value>
<value>请多多关照</value>
</array>
</property>
<!-- list注入 -->
<property name="list">
<list>
<value>小丁</value>
<value>520</value>
<value>1314</value>
</list>
</property>
<!-- map注入 -->
<property name="map" >
<map>
<entry key="小丁" value="123456"></entry>
<entry>
<key><value>你好</value></key>
<value>我是</value>
</entry>
</map>
</property>
<!-- set注入 -->
<property name="set">
<set>
<value>我是</value>
<value>set</value>
<value>ArraySet、TreeSet</value>
</set>
</property>
<!-- properties注入 -->
<property name="properties">
<props>
<prop key="你好">pros</prop>
<prop key="今天是">三八妇女节</prop>
</props>
</property>
</bean>
<!--
P(属性: properties)命名空间 , 属性依然要设置set方法
如果该类的属性没有set方法,则无法注入,会报错
需要xml头部加入约束文件
导入约束 : xmlns:p="http://www.springframework.org/schema/p"
-->
<bean id="people2" class="com.njxh.bean.People" p:name="你好"/>
<!--
C(构造: Constructor)命名空间 , 属性依然要设置set方法
如果该类没有有参构造方法,则无法注入,会报错
需要xml头部加入约束文件
导入约束 : xmlns:c="http://www.springframework.org/schema/c"
-->
<bean id="people3" class="com.njxh.bean.People" c:name="asa,sd" c:list="asdf"></bean>
</beans>
注意:
1、p和c命名空间注入,只能注入一写简单的属性,c命名空间能注入的类型比p要多一些
2、@org.junit.Test 是测试用的,如果不会使用,可以自行去掉,不影响程序的执行
bean的作用域和自动装配
bean作用域
看作用域之前:先了解一下什么是单例模式:https://blog.csdn.net/qq_35098526/article/details/79893628
在Spring中,那些组成应用程序的主体以及由Spring IOC容器所管理的对象,被称之为bean。
简单的将,bean就是由IOC容器初始化,装配以及管理的对象。
作用域 | 描述 |
---|---|
singleton | 在spring IoC容器仅存在一个Bean实例,Bean以单例方式存在,bean作用域范围的默认值。 |
prototype | 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行newXxxBean()。 |
request | 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于web的Spring WebApplicationContext环境。 |
session | 同一个HTTP Session共享一个Bean,不同Session使用不同的Bean。该作用域仅适用于web的Spring WebApplicationContext环境。 |
application | 限定一个Bean的作用域为ServletContext 的生命周期。该作用域仅适用于web的Spring WebApplicationContext环境。 |
//狗类
public class Dog {
private String name;
public Dog(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
//猫类
public class Car {
private String name;
public Car() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
'}';
}
}
<!-- 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:p="http://www.springframework.org/schema/p"
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" >
<!--
Spring的作用域分别为:singleton、prototype、request、session、application
使用scope属性进行赋值
-->
<!-- 单利模式 -->
<bean id="dog" class="com.njxh.bean.Dog" scope="singleton"></bean>
<!-- 多例模式 -->
<bean id="car" class="com.njxh.bean.Car" scope="prototype"></bean>
</beans>
//测试
public class Test {
private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//单利模式
public static void test() {
//获取对象
Dog dog = context.getBean("dog", Dog.class);
Dog dog1 = context.getBean("dog", Dog.class);
//对比对象地址是否一样
System.out.println("单例模式:" + (dog == dog1));
}
//多例模式
public static void test2() {
//获取对象
Car car = context.getBean("car", Car.class);
Car car1 = context.getBean("car", Car.class);
//对比对象地址是否一样
System.out.println("多例模式:" + (car == car1));
}
public static void main(String[] args) {
//测试
test();
test2();
}
}
运行结果:
bean自动装配
- 自动装配是使用Spring满足bean依赖的一种方法
- Spring会在应用上下中为某个bean寻找依赖的bean
- Spring中bean有三种装配机制,分别是:
- 在xml中显示配置
- 在Java中显示配置
- 隐式的bean发现机制和自动装配
这里我们将第三种:自动化的装配bean。
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
1、组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
2、自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;
组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少
推荐不使用自动装配xml配置,而使用注解
自动装配使用:autowire属性来实现
byName 根据名称自动装配
可以根据bean中属性的名称,进行上下文查找相应的id,如果名称相同,则自动装配。
缺点:由于我们手动配置xml过程中,常常发生字母缺漏和大小写错误,而无法对其进行检查,使用开发效率低下
注意:
1、如果一个xml中有两个bean的id相同,那么自动配置时,优先匹配上面一个
2、byName是根据bean对象属性的set方法名,例如setCar,将获取将set去掉并且首字母小写的字符串,
即car
3、Spring在上下文查找,是否有此字符串名称id的对象,有就注入,没有就报错
4、如果Spring查找不到对象的字符串id,就报空指针异常
byType 根据类型自动装配
使用byType必须要保证:同一类型的对象,在Spring容器中唯一。
如果不唯一,就会报不唯一异常。
由于这个根据类型来自动装配的,所以即使id名字不同,也不影响
自动装配总代码
//狗类
public class Dog {
public void run() {
System.out.println("我是小狗");
}
}
//猫类
public class Car {
public void run() {
System.out.println("我是小猫");
}
}
//人类
public class Author {
private String name;
private Dog dog;
private Car car;
public Author() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
//测试
public class Test {
private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//byName自动装配
public static void test() {
//获取对象
Author author = context.getBean("author", Author.class);
//调用方法
author.getDog().run();
author.getDog().run();
System.out.println(author.getName());
}
//byType自动装配
public static void test2() {
//获取对象
Author author = context.getBean("author2", Author.class);
//调用方法
author.getDog().run();
author.getDog().run();
System.out.println(author.getName());
}
public static void main(String[] args) {
//测试数据
test();
test2();
}
}
<!-- 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:p="http://www.springframework.org/schema/p"
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" >
<bean id="dog" class="com.njxh.bean.Dog"></bean>
<bean id="car" class="com.njxh.bean.Car"></bean>
<!-- byName 根据名称自动装配 -->
<bean id="author" class="com.njxh.bean.Author" autowire="byName">
<property name="name" value="小丁"></property>
</bean>
<!-- byType 根据类型自动装配 -->
<bean id="author2" class="com.njxh.bean.Author" autowire="byType">
<property name="name" value="小丁520"></property>
</bean>
</beans>
运行结果:
byName错误代码
<!-- id名称跟author类dog属性的set方法,去掉set的之后名称不一致 -->
<bean id="dog2" class="com.njxh.bean.Dog"></bean>
<bean id="car" class="com.njxh.bean.Car"></bean>
<bean id="author" class="com.njxh.bean.Author" autowire="byName">
<property name="name" value="小丁"></property>
</bean>
byType错误代码
<!-- bean对象的类型在Spring容器,不唯一 -->
<bean id="dog" class="com.njxh.bean.Dog"></bean>
<bean id="dog2" class="com.njxh.bean.Dog"></bean>
<bean id="car" class="com.njxh.bean.Car"></bean>
<bean id="author2" class="com.njxh.bean.Author" autowire="byType">
<property name="name" value="小丁520"></property>
</bean>
使用注解为属性赋值
注解使用须知
jdk1.5开始支持注解,spring2.5开始全面支持注解。
1、xml头部导入context约束
xmlns:context="http://www.springframework.org/schema/context"
<!-- 这个加入 xsi:schemaLocation 里面跟原本的值用一个“”号 -->
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<!-- 就像这样 -->
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"
2、加入注解驱动
<context:annotation-config/>
@Autowired 注解
<!-- 允许对象为空,但是bean必须存在 -->
@Autowired(required = false)
private Dog dog;
<!-- 默认是根据byType来查找,找不到,根据byName来查找 -->
@Autowired
private Car car;
<!-- 如果Spring容器中,一个bean不唯一,且名字与属性的名称不同,可以使用Qualifier -->
<!-- Qualifier 不能单独使用 -->
@Autowired
@Qualifier(value = "tiger1")
private Tiger tiger;
扩展 @Nullable
表示某个字段为空
public class Tiger {
private String name = "老虎";
public Tiger() {}
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
}
@Resource注解
<!-- 默认是根据byName来查找,找不到,就用byType,都找不到就报错 -->
@Resource
private Dog dog;
<!-- 指定 bean对象的id 注入,使用name后,就会转入byName查找,找不到就报错 -->
@Resource(name = "car")
private Car car;
@Resource(name = "tiger1")
private Tiger tiger;
Autowired 与Resource注解的区别:
1、autowired执行顺序是先byType,后byName
2、resource执行顺序是先byName,后byType
3、被autowired和resource注解定义的属性,可以不定义set方法
4、autowired和resource可以在set方法上使用
全部代码
//猫类
public class Car {
private String name = "猫咪";
public Car() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//狗类
public class Dog {
private String name = "狗狗";
public Dog() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//老虎类
public class Tiger {
private String name = "老虎";
public Tiger() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//人类
public class People {
private String name;
//表示这个属性对象可以为null,但是bean必须存在
@Autowired(required = false)
private Dog dog;
//Autowired 默认根据byType来查找bean,查找不到就会用byName来查找
//使用Autowired 可以不写set方法,Autowired可以使用在set方法上使用
@Autowired
private Car car;
//如果xml的有多个同一类型的bean对象,并且bean的id名称跟属性的名称不一致
//可以使用Autowired 配合 Qualifier使用
//Qualifier 指定一个bean对象
@Autowired
@Qualifier(value = "tiger1")
private Tiger tiger;
public People() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Tiger getTiger() {
return tiger;
}
public void setTiger(Tiger tiger) {
this.tiger = tiger;
}
}
//人类
public class People2 {
private String name;
//Resource 是Java中自带的注解
//根据首先bean的名称,来查询,找不到在根据类型来查询
@Resource
private Dog dog;
//Resource name 指定一个bean对象的id
//Resource 使用name指定,只会根据id来查找,找不到就报错
@Resource(name = "car")
private Car car;
@Resource(name = "tiger1")
private Tiger tiger;
public People2() {}
public void setName(String name) {
this.name = name;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public void setCar(Car car) {
this.car = car;
}
public void setTiger(Tiger tiger) {
this.tiger = tiger;
}
public String getName() {
return name;
}
public Dog getDog() {
return dog;
}
public Car getCar() {
return car;
}
public Tiger getTiger() {
return tiger;
}
}
//测试
public class Test {
private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//Autowired注解的使用
public static void test() {
//获取对象
People people = context.getBean("people", People.class);
//打印数据
System.out.println(people.getDog().getName());
System.out.println(people.getCar().getName());
System.out.println(people.getTiger().getName());
}
//Resource注解使用
public static void test2() {
//获取对象
People2 people2 = context.getBean("people2", People2.class);
//打印数据
System.out.println(people2.getDog().getName());
System.out.println(people2.getCar().getName());
System.out.println(people2.getTiger().getName());
}
public static void main(String[] args) {
//测试
// test();
test2();
}
}
使用注解开发
说明
Spring4之后,想要使用注解形式,必须得要引入aop的包
在Spring配置文件中,引入一个Context约束文件
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
使用注解定义bean
我们之前都是使用bean的标签进行bean注入,但是实际开发中,我们一般都会使用注解!
1、配置扫描哪些包下的注解
<!--指定注解扫描包 放入Spring配置文件中-->
<context:component-scan base-package="com.kuang.pojo"/>
2、在指定包下编写类,增加注解
//用户
@Component("user")
//相当于 Spring配置文件中的 <bean id="user" class="当前注解的类" />
public class User {
private String name = "小丁";
public String getName() {
return name;
}
}
//测试
public class Test {
private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//bean的注解测试
public static void test() {
//获取对象
User user = context.getBean("user", User.class);
//打印数据
System.out.println(user.getName());
}
public static void main(String[] args) {
//测试结果
test();
}
}
属性注入
属性注入
@Component("user")
public class User {
@Value("小丁520")
//相当于 Spring配置文件中 <property name="name" value="小丁520"/>
private String name;
public String getName() {
return name;
}
}
set方式上使用注解
@Component("user")
public class User {
private String name;
@Value("小丁520")
public String getName() {
return name;
}
}
衍生注解
我们这些注解,就是替代了配置文件当中配置步骤而已!更加的方便快捷!
@Component三个衍生注解
为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样
- @Controller:server层
- @Service:service层
- @Repository:dao层
写上这些注解,就相当于将这个类交给Spring管理装配了!
注意:
1、这些注解定义在类上,如果类名是一个单词,那么bean的id就是小写的
2、如果类由多个单词组成,使用注解后,且不指定名称那么,bean的id是首个单词小写,
其余单词首字母大写,其他字母小写
作用域
@Scope
-
singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁
-
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Service
@Scope("singleton") //将当前类设置为单例模式
public class UserService {
}
xml与注解小结
XML与注解的比较
- XML可以适用于任何场景,结构清晰,维护方便
- 注解不是自己提供的类使用不了,开发简单方便
XML与注解整合开(推荐最佳实践)
- xml管理bean
- 注解完成属性注入
- 使用过程中,可以不同扫描,扫描是为了类上的注解
<context:annotation-config/>
作用:
- 进行注解驱动注册,从而使注解生效
- 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
- 如果不加扫描包,就需要手动配置bean
- 如果不加注解驱动,则注入的值为null!
基于Java类配置注解
JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。
测试:
1、编写一个实体类,Dog
@Component //将这个类标注为Spring的一个组件,放到容器中!
public class Dog {
private String name = "狗狗";
public String getName() {
return name;
}
}
2、新建一个config配置包,编写一个MyConfig配置类
//Configuration 本身也是一个Component
//所以当一个类被 Configuration 注解定义后,这个类就被Spirng托管了
//而这个被定义的类,相当于Spring xml配置文件
@Configuration
//ComponentScan 相当于Spring的 注解扫描包
//<context:component-scan base-package="要扫描类的路径"/>
@ComponentScan("com.njxh")
public class MyConfig {
//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
@Bean
public Dog getDog() {
return new Dog();
}
}
导入其他配置如何做呢?
1、我们再编写一个配置类!
@Configuration
public class MyConfig2 {
//定义一个bean
@Bean
public Dog dog2() {
return new Dog();
}
}
2、在之前的配置类中我们来选择导入这个配置类
@Configuration
@ComponentScan("com.njxh")
//相当于一个Spirng中的 <import resource="{path}/beans.xml" />
@Import(MyConfig2.class)
public class MyConfig {
//通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
@Bean
public Dog getDog() {
return new Dog();
}
}
测试类
public class Test {
private static ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//JavaConfig测试
public static void test() {
//获取对象
Dog dog = context.getBean("getDog", Dog.class);
//打印数据
System.out.println(dog.getName());
}
//ComponentScan测试
public static void test2() {
//获取对象
Dog dog = context.getBean("dog", Dog.class);
//打印数据
System.out.println(dog.getName());
}
//Import测试
public static void test3() {
//获取对象
Dog dog = context.getBean("dog2", Dog.class);
//打印数据
System.out.println(dog.getName());
}
public static void main(String[] args) {
//测试
// test();
// test2();
test3();
}
}
关于这种Java类的配置方式,我们在之后的SpringBoot 和 SpringCloud中还会大量看到,我们需要知道这些注解的作用即可!
静态代理模式
图解代理模式
静态代理角色分析
- 抽象角色:一般使用接口或抽象类来实现
- 真实角色:被代理的角色
- 代理角色:代理真实角色;代理真实角色后,一般会做一些附属的操作
- 客户:使用代理角色来进行一些操作
//租房
public interface Rent {
//定义租房的方法
public void rent();
}
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房子出租!");
}
}
//中介
public class Proxy implements Rent{
private Host host;
public Proxy() {}
public Proxy(Host host) {this.host = host;}
@Override
public void rent() {
host.rent();
this.seeHouse();
this.fare();
}
//带房客看房
public void seeHouse() {
System.out.println("带房客看房");
}
//收中介费
public void fare() {
System.out.println("手中介费");
}
}
//客户类
public class Cilent {
public static void main(String[] args) {
//房东要租房
Host host = new Host();
//中介帮助房东
Proxy proxy = new Proxy(host);
//租房找中介
proxy.rent();
}
}
运行结果:
分析:在这个过程中,你直接接触的就是中介,就如同现实生活中的样子,你看不到房东,但是你依旧租到了房东的房子通过代理,这就是所谓的代理模式,程序源自于生活,所以学编程的人,一般能够更加抽象的看待生活中发生的事情。
静态代理的好处
- 可以使得我们的真实角色更加纯粹,不在关注一些公共的事情
- 公共的业务由代理来完成,实现了业务的分工
- 公共业务发生扩展时变得更加集中和方便
缺点:
- 类多了,多了代理类,工作量变大了,开发效率降低
我们想要静态代理的好处,又不想要静态代理的缺点,所以,就有了动态代理!
深入理解单例模式
1、创建一个抽象角色,比如我们平时做的用户业务,抽象起来就是增删改查
//用户业务接口
public interface UserService {
//添加方法
public void add();
//修改方法
public void update();
//查询方法
public void query();
//删除方法
public void delete();
}
2、我们需要一个真实对象来完成这些增删改查操作
//定义了一个用户业务实现类(真实角色),来实现这些方法
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("添加用户");
}
@Override
public void update() {
System.out.println("修改用户");
}
@Override
public void query() {
System.out.println("查询用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
}
3、需求来了,现在我们需要增加一个日志功能,怎么实现!
- 思路1:在实现类上增加代码【麻烦!】
- 思路2:使用代理来做,能够不改变原来的业务情况下,实现此功能就是最好的了?
4、设置一个代理类来处理日志!代理角色
//定义一个log日志类
public class UserServiceProxy implements UserService{
private UserServiceImpl user;
public UserServiceProxy() {}
public UserServiceProxy(UserServiceImpl user) {
this.user = user;
}
@Override
public void add() {
this.log("add");
user.add();
}
@Override
public void update() {
this.log("update");
user.update();
}
@Override
public void query() {
this.log("query");
user.query();
}
@Override
public void delete() {
this.log("delete");
user.delete();
}
public void log(String msg) {
System.out.println("执行了"+msg+"方法");
}
}
5、测试访问类
public class Cilent {
public static void main(String[] args) {
//真实业务
UserServiceImpl user = new UserServiceImpl();
//代理类
UserServiceProxy user2 = new UserServiceProxy(user);
//使用代理类实现日志功能!
user2.add();
}
}
OK,到了现在代理模式大家应该都没有什么问题了,重点大家需要理解其中的思想;
我们在不改变原来的代码的情况下,实现了对原有功能的增强,这是AOP中最核心的思想
聊聊AOP:纵向开发,横向开发
动态代理模式
动态代理模式
- 动态代理的角色和静态代理的一样
- 动态代理的代理类是动态生成的,静态代理的代理类是我们提前写好的
- 动态代理分为两类:一类是基于接口动态代理,一类是基于类的动态代理
- 基于接口的动态代理------JDK动态代理
- 基于类的动态代理–cglib
- 现在用的比较多的是javasist来生成动态代理,百度一下javasist
- 我们这里使用JDK的原生代码来实现,其余的道理都是一样的
JDK的动态代理需要两个类
核心:InvocationHandler 和Proxy,打开JDK帮助文档看看
【InvocationHandler:调用处理程序】
Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
【Proxy : 代理】
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
代码实现
抽象角色和真实角色和之前的一样
//抽象角色:租房
public interface Rent {
public void rent();
}
Host.java 即真实角色
//真实角色: 房东,房东要出租房子
public class Host implements Rent{
public void rent() {
System.out.println("房屋出租");
}
}
ProxyInvocationHandler.java 即代理角色
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理类,重点是第二个参数,获取要代理的抽象角色!之前都是一个角色,现在可以代理一类角色
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),this);
}
// proxy : 代理类 method : 代理类的调用处理程序的方法对象.
// 处理代理实例上的方法调用并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//核心:本质利用反射实现!
Object result = method.invoke(rent, args);
fare();
return result;
}
//看房
public void seeHouse(){
System.out.println("带房客看房");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
}
Client.java 租客
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理实例的调用处理程序
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host); //将真实角色放置进去!
Rent proxy = (Rent)pih.getProxy(); //动态生成对应的代理类!
proxy.rent();
}
}
核心:一个动态代理,一般代理某一类业务,一个动态代理可以代理多个类,代理的是接口!
深入理解
我们来使用动态代理实现代理我们后面写的UserService!
我们也可以编写一个通用的动态代理实现的类!所有的代理对象设置为Object即可!
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);
}
// proxy : 代理类
// method : 代理类的调用处理程序的方法对象.
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 methodName){
System.out.println("执行了"+methodName+"方法");
}
}
测试
public class Test {
public static void main(String[] args) {
//真实对象
UserServiceImpl userService = new UserServiceImpl();
//代理对象的调用处理程序
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService); //设置要代理的对象
UserService proxy = (UserService)pih.getProxy(); //动态生成代理类!
proxy.delete();
}
}
测试,增删改查,查看结果!
动态代理的好处
静态代理有的它都有,静态代理没有的,它也有!
- 可以使得我们的真实角色更加纯粹,不在关注一些公共的事情
- 公共的业务由代理完成,实现了业务的分工
- 公共业务发生扩展时变得更加集中和方便
- 一个动态代理可以代理多个类,代理的是接口!
AOP的使用
什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DKV5OU3S-1615946896321)(E:\自学笔记\狂神说Java\Spring框架\image\AOP原理图.png)]
AOP在Spring中的作用
提供声明式事物,允许用户自定义切面
以下名词需要了解一下:
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
- 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知 执行的 “地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即 Aop 在 不改变原有使用代码的情况下 , 去增加新的功能 .
使用Spring 实现AOP
【重点】使用AOP,需要导入一个依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
第一种方式:
通过Spring API实现
首先编写我们的业务接口和实现类
//用户逻辑业务接口
public interface UserService {
public void add();
public void update();
public void delete();
public void query();
}
//实现类
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("添加用户");
}
@Override
public void update() {
System.out.println("修改用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void query() {
System.out.println("查询用户");
}
}
在写两个增强类
//前置通知
public class Log implements MethodBeforeAdvice {
//method :要执行目标对象的方法
//objects :被调用的方法的参数
//o : 目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"类的"+method.getName()+"方法被执行了");
}
}
//后置通知
public class AfterLog implements AfterReturningAdvice {
//o :返回的对象
//method : 被调用的方法
//args : 被调用的方法的对象的参数
//o1 : 被调用的目标对象
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println(o1.getClass().getName()+"类"+method.getName()+"方法执成,"+o+"返回值");
}
}
在Spring xml文档中导入aop的约束,注册bean,配置aop
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="user" class="com.njxh.service.UserServiceImpl"></bean>
<bean id="log" class="com.njxh.config.Log"></bean>
<bean id="afterLog" class="com.njxh.config.AfterLog"></bean>
<!-- 第一种方法 通过API的方法配置 aop -->
<aop:config>
<!-- 配置切入点 expression 表达式匹配要执行的方法 execution(* 表示类型 切入的位置(*当前包下的所有类 (..)当前类中的所有方法) -->
<aop:pointcut id="pointcut" expression="execution(* com.njxh.service.UserServiceImpl.*(..))"/>
<!-- 配置通知 advice-ref执行的方法 pointcut-ref切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"></aop:advisor>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
</beans>
测试
public class Test {
private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
public static void main(String[] args) {
//获取对象
UserService userService = (UserService)context.getBean("user");
//执行方法
userService.add();
}
}
Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理
第二种方式:
自定义切面类来实现AOP
先了解一下:JoinPoint这个类,在Spring AOP中被称为连接点,与切入点匹配的执行点
这个类有什么作用呢?
可以通过这个类来获取,被切入对象方法的一些信息,
在切面方法中添加JoinPoint,就可以获取到切入
对象方法的一些信息,比如方法名、参数、类的信息等
常用方法:
方法名 | 功能 |
---|---|
Signature getSignature() | 获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息 |
Object[] getArgs(); | 获取切入对象方法的所有参数,也可以根据索引 |
Object getTarget(); | 获取被代理的对象 |
Object getThis(); | 获取代理对象 |
定义一个自定切面类
public class Log {
//前置通知
public void before(JoinPoint jp) {
//获取切入对象方法的名称
System.out.println(jp.getTarget().getClass().getName()+"类,执行"+ jp.getSignature().getName()+"方法");
}
//后置通知
public void afterAdvice(JoinPoint jp) {
//获取切入对象方法的被代理对象和代理对象
//p.getArgs()[0]+"第0个参数,"
System.out.println(jp.getTarget()+"被代理对象,"+jp.getThis()+"代理对象");
}
//环绕通知
public void aroundAdivce(ProceedingJoinPoint jp) throws Throwable {
System.out.println("执行方法前");
//核心,底层就是反射
Object obj = jp.proceed();
System.out.println("执行方法后");
}
//返回通知
public void afterReturn(JoinPoint jp) {
System.out.println("返回通知");
}
//异常抛出
public void afterException(JoinPoint jp,Throwable e) {
System.out.println("异常通知");
System.out.println("异常信息:"+e.getMessage());
}
}
在Spring中配置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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="log" class="com.njxh.config.Log"></bean>
<bean id="user" class="com.njxh.service.UserServiceImpl"></bean>
<!-- 自定义切面实现AOP -->
<aop:config>
<!-- 引入切面类 -->
<aop:aspect ref="log">
<!-- 定义切入点 -->
<aop:pointcut id="pointcut" expression="execution(* com.njxh.service.*.*(..))"/>
<!-- 定义通知 -->
<aop:around method="aroundAdivce" pointcut-ref="pointcut"></aop:around>
<aop:before method="before" pointcut-ref="pointcut"></aop:before>
<aop:after method="afterAdvice" pointcut-ref="pointcut"></aop:after>
<aop:after-returning method="afterReturn" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterException" pointcut-ref="pointcut" throwing="e"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
测试
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//获取对象
UserService userService = (UserService) context.getBean("user");
userService.add();
}
}
第三种方式
通过注解实现AOP
定义注解类
@Aspect
public class Log {
//前置通知
@Before("execution(* com.njxh.service.*.*(..))")
public void before(JoinPoint jp) {
//获取切入对象方法的名称
System.out.println(jp.getTarget().getClass().getName()+"类,执行"+ jp.getSignature().getName()+"方法");
}
//后置通知
@After("execution(* com.njxh.service.*.*(..))")
public void afterAdvice(JoinPoint jp) {
//获取切入对象方法的被代理对象和代理对象
//p.getArgs()[0]+"第0个参数,"
System.out.println(jp.getTarget()+"被代理对象,"+jp.getThis()+"代理对象");
}
//环绕通知
@Around("execution(* com.njxh.service.*.*(..))")
public void aroundAdivce(ProceedingJoinPoint jp) throws Throwable {
System.out.println("执行方法前");
//核心,底层就是反射
Object obj = jp.proceed();
System.out.println("执行方法后");
}
//返回通知
@AfterReturning("execution(* com.njxh.service.*.*(..))")
public void afterReturn(JoinPoint jp) {
System.out.println("返回通知");
}
//异常抛出
@AfterThrowing(value = "execution(* com.njxh.service.*.*(..))",throwing = "e")
public void afterException(JoinPoint jp,Throwable e) {
System.out.println("异常通知");
System.out.println("异常信息:"+e.getMessage());
}
}
在Spring中配置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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean -->
<bean id="user" class="com.njxh.service.UserServiceImpl"/>
<bean id="log" class="com.njxh.config.Log"></bean>
<!--
第三种方式:注解实现
-->
<aop:aspectj-autoproxy expose-proxy="false"/>
</beans>
测试:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService =(UserService) context.getBean("user");
userService.add();
}
}
注意:
1、自定义切面类的方法执行顺序是根据AOP配置时的顺序来的。
2、注解实现AOP,如果环绕和前置以及后置同在,那么先执行环绕》前置》后置
3、注解实现AOP,也可以配合其他注解使用
aop:aspectj-autoproxy:说明
通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了
<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。
MyBatis回顾和MyBatis整合
回忆MyBatis
第一步,导入相关jar
//spring-mvc
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.4</version>
</dependency>
//annotation
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
//aspectjweaver
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
//mybatis-spring
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
//mybatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
//junit
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
//mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
配置Maven静态资源过滤问题
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
第二步:编写配置文件
<?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.njxh.pojo"/>
</typeAliases>
<!-- 配置连接驱动 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="dingtianci123"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射 根据包名自动加载所有映射文件 -->
<mappers>
<package name="com.njxh.mapper"/>
</mappers>
</configuration>
第三部代码实现
定义工具类
public class MyBatis {
public static SqlSession getSqlSeesion() {
//加载MyBatis配置文件
String resource = "MyBatis.xml";
//定义IO流
Reader reader = null;
//定义工厂类
SqlSessionFactory sqlSessionFactory = null;
//异常抛出
try {
reader = Resources.getResourceAsReader(resource);
}catch (Exception e){
e.printStackTrace();
}
//判断reader是否为null
if (reader != null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
//返回类型
return sqlSessionFactory.openSession();
}
}
定义数据封装类
public class User {
private int id;
private String name;
private int age;
private char sex;
public User() {}
public User(int id,String name,int age,char sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public char getSex() {
return sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
定义映射接口和xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njxh.mapper.UserMapper">
<select id="selectUser" resultType="com.njxh.pojo.User">
select * from user
</select>
</mapper>
public interface UserMapper {
public List<User> selectUser();
}
测试
public class Test {
public static void main(String[] args) {
//获取sqlseesion对象
SqlSession session = MyBatis.getSqlSeesion();
//加载UserMapper接口
UserMapper userMapper = session.getMapper(UserMapper.class);
//执行SQL语句方法
List<User> list = userMapper.selectUser();
//打印数据
System.out.println(list);
}
}
运行结果:
学习MyBatis-Spring
引入Spring之前需要了解mybatis-spring包中的一些重要类;
http://mybatis.org/spring/zh/index.html
什么是 MyBatis-Spring?
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
知识基础
在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要
MyBatis-Spring 需要以下版本:
MyBatis-Spring | MyBatis | Spring 框架 | Spring Batch | Java |
---|---|---|---|---|
2.0 | 3.5+ | 5.0+ | 4.0+ | Java 8+ |
1.3 | 3.4+ | 3.2.2+ | 2.1+ | Java 6+ |
如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个 SqlSessionFactory 和至少一个数据映射器类。
配置数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="dingtianci123"/>
</bean>
在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:
在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:
<bean id="sqlSeesionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 关联MyBatis -->
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations" value="classpath:com/njxh/mapper/*.xml"/>
</bean>
注意:SqlSessionFactory需要一个 DataSource(数据源)。这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建。
在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession。一旦你获得一个 session 之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session。
SqlSessionFactory有一个唯一的必要属性:用于 JDBC 的 DataSource。这可以是任意的 DataSource 对象,它的配置方法和其它 Spring 数据库连接是一样的。
一个常用的属性是 configLocation,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 < settings> 或 < typeAliases>元素。
需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置(),数据源()和 MyBatis 的事务管理器()都会被忽略。SqlSessionFactoryBean 会创建它自有的 MyBatis 环境配置(Environment),并按要求设置自定义环境的值。
SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。
模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
现在,这个 bean 就可以直接注入到你的 DAO bean 中了。你需要在你的 bean 中添加一个 SqlSession 属性,就像下面这样:
public class UserDaoImpl implements UserDao {
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public User getUser(String userId) {
return sqlSession.getMapper...;
}
}
按下面这样,注入 SqlSessionTemplate:
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession" />
</bean>
Spring整合MyBatis方式一
1、导入相关jar包
回忆MyBatis的jar
2、定义MyBatis、Spring的配置文件
MyBatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 定义别名 -->
<typeAliases>
<package name="com.njxh.pojo"/>
</typeAliases>
</configuration>
Spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置数据源替换mybatis的数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="dingtianci123"/>
</bean>
<!-- 配置SqlSeesionFactory,关联MyBatis -->
<bean id="sqlSeesionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 关联MyBatis -->
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations" value="classpath:com/njxh/mapper/*.xml"/>
</bean>
<!-- 注册SqlSeesionTempate, 关联sqlSeesionFactory-->
<bean id="sqlSeesion" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 利用构造器注入 -->
<constructor-arg index="0" ref="sqlSeesionFactory"/>
</bean>
</beans>
3、定义数据封装类
上面定义的User
4、定义映射接口和xml文件
上面定义的UserMapper.java、UserMapper.xml
5、定义接口实现类
public class UserDaoImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
//sqlSession已经由Spsring接管,不需要我们去创建
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> selectUser() {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.selectUser();
}
}
6、注册bean
<!-- 注册bean -->
<bean id="userDaoImpl" class="com.njxh.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSeesion"></property>
</bean>
7、测试
public class Test {
public static void main(String[] args) {
//加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans-context.xml");
//获取对象
UserDaoImpl userDao = context.getBean("userDaoImpl", UserDaoImpl.class);
System.out.println(userDao.selectUser());
}
}
Spring整合MyBatis方式二
mybatis-spring1.2.3版以上的才有这个 .
官方文档截图 :
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zllViYuC-1615946896325)(E:\自学笔记\狂神说Java\Spring框架\image\SqlSession使用DaoSupport.png)]
dao继承SqlSessionDaoSupport 类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看
测试:
1、将我们上面写好的UserDaoImpl类,修改一下
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> selectUser() {
return this.getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
2、修改bean,之前定义的SqlSessionTemplate可以删除了
<bean id="userDaoImpl" class="com.njxh.mapper.UserDaoImpl">
<property name="sqlSession" ref="sqlSeesion"></property>
</bean>
3、测试
public class Test {
public static void main(String[] args) {
//加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans-context.xml");
//获取对象
UserDaoImpl userDao = context.getBean("userDaoImpl", UserDaoImpl.class);
System.out.println(userDao.selectUser());
}
}
事物的使用
回顾事物
- 事物在项目发开过程中非常重要,涉及到数据的一致性的问题,不容马虎!
- 事物管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。
事物四个属性ACID
- 原子性
- 事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
- 一致性
- 一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
- 隔离性
- 可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
- 持久性
- 事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
测试
将上面的代码拷贝到一个新项目中
在之前的案例中,我们给UserMapper接口新增两个方法,删除和增加用户;
//添加用户
public int addUser(User user);
//删除用户
public int deleteUser(int id);
mapper文件,我们故意把deletes写错,测试!
<insert id="addUser" parameterType="com.njxh.pojo.User" >
insert into user values(#{id},#{name},#{age},#{sex})
</insert>
<delete id="deleteUser" parameterType="int">
deletes from user where id = #{id}
</delete>
编写接口的实现类,在实现类中,我们去操作一波
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> selectUser() {
//在查询前,添加一条数据、删除一条
addUser(new User(4,"小王",25,'男'));
deleteUser(3);
return this.getSqlSession().getMapper(UserMapper.class).selectUser();
}
@Override
public int addUser(User user) {
return this.getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return this.getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
测试
public class Test {
public static void main(String[] args) {
//加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans-context.xml");
//获取对象
UserMapper userMapper = context.getBean("userDaoImpl", UserMapper.class);
//调用方法
System.out.println(userMapper.selectUser());
}
}
报错:sql异常,delete写错了
结果 :插入成功!
没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!
以前我们都需要自己手动管理事务,十分麻烦!
但是Spring给我们提供了事务管理,我们只需要配置即可;
Spring中的事务管理
Spring在不同的事务管理API之上定义一个抽象层,使得开发人员不必了解底层的事务管理
API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式事务管理
编程式事务管理
- 将事物管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事物管理代码声明式事务管理**
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
使用Spring管理事务,注意头文件的约束导入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器
- 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
- 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。
JDBC事务
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
配置好事务管理器后我们需要去配置事务的通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 规定方法的前缀,规定哪些方法使用事物,配置事物的传播特性 -->
<tx:method name="add *" propagation="REQUIRED"/>
<tx:method name="update *" propagation="REQUIRED"/>
<tx:method name="delete *" propagation="REQUIRED"/>
<tx:method name="query *" read-only="true"/>
<tx:method name="get *" read-only="true"/>
<tx:method name="set *" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
spring事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!
配置AOP
导入aop的头文件!
<!-- 配置AOP切面 -->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut id="pointcut" expression="execution(* com.njxh.dao.*.*(..))"/>
<!-- 引入事物 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
进行测试
删掉刚才插入的数据,再次测试!
public class Test {
public static void main(String[] args) {
//加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans-context.xml");
//获取对象
UserMapper userMapper = context.getBean("userDaoImpl", UserMapper.class);
//调用方法
System.out.println(userMapper.selectUser());
}
}
思考问题?
为什么需要配置事务?
- 如果不配置,就需要我们手动提交控制事务;
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
免责声明
本内容来源于狂神说Java Spring教程,自己整理的,跟官方笔记一样,如果侵权请联系删除,我的邮箱:2957754055@qq.com。