目录
Spring 中的 AOP
spring 的 aop就是通过配置的方式实现动态代理
01.AOP相关术语
Joinpoint(连接点)
:
- 所谓连接点是指那些
可以
被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点。 - 通俗的说就是被代理类中的
所有方法
。
Pointcut(切入点)
:
- 所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。
- 通俗的说就是被代理类中的
被代理的方法
,因为被代理类中并不是所有的方法
都被代理了。
Advice(通知/增强):
- 所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。
- 通俗的说就是对被代理的方法进行增强的代码。
- 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知
- 前置通知:在被代理方法执行之前执行
- 后置通知:在被代理方法执行之后执行
- 异常通知:在被代理方法执行出错的时候执行
- 最终通知:无论怎样都会执行
- 注意:后置通知和异常通知只能有一个会被执行,因为发生异常执行异常通知,然后就不会继续向下执行,自然后置通知也就不会被执行,反之亦然。
Introduction(引介):
- 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些
方法
或属性
。
Target(目标对象):
- 代理的目标对象
- 通俗的说就是被代理的对象
Weaving(织入):
- 是指把增强应用到目标对象来创建新的代理对象的过程,spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
- 通俗的说就是让增强的代码(通知)植入到待增强的方法(切入点)中。
Proxy(代理) :
- 一个类被 AOP 织入增强后,就产生一个结果代理类。
Aspect(切面):
- 是切入点和通知(引介)的结合
- 通俗的说就是建立切入点和通知方法在创建时的对应关系
02.spring 的 AOP 要干什么事
开发阶段(我们做的)
- 1.编写核心业务代码(前期),
- 2.把公用代码抽取出来,制作成通知(后期)(把公共的代码通过增强的的方式织入到方法中)
- 3.在配置文件中,声明切入点与通知间的关系,即切面(重点)
运行阶段( Spring 框架完成的)
- 1.Spring 框架监控切入点方法的执行,一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
03.关于代理的选择
看过动态代理就知道动态代理分为两种:基于接口的动态代理
和基于子类的动态代理(cglib)
- 当代理类实现了某个接口的时候:使用基于接口的动态代理
- 当代理类没有实现任何接口的时候:使用基于子类的动态代理(cglib)
04.基于 XML 的 AOP 配置
大致步骤为:
- 1.导入依赖jar包或者坐标
- 2.创建 spring 的配置文件(bean.xml)并导入约束(AOP约束)
- 3.在配置文件中配置 spring 的 ioc(IOC内容)
- 4.抽取公共代码制作成通知(Transaction事务)
下面是aop配置
- 5.把通知类用 bean 标签配置起来
- 6.使用 aop:config 声明 aop 配置
- 7.使用 aop:aspect 配置切面
- 8.使用 aop:pointcut 配置切入点表达式
- 9.使用 aop:xxx 配置对应的通知类型
05.AOP配置标签详解
5.1.aop:config标签
aop:config
标签:表明开始AOP的配置
<aop:config>
<!-- 添加内容-->
</aop:config>
5.2.aop:aspect标签
aop:aspect
标签:表明配置切面
- 标签位置:aop:config标签内部
- id属性:是给切面提供一个唯一标识(可随意指定,一般都只指定有意义的名字)
- ref属性:是指定通知类bean的Id
<aop:config> <!--配置切面 --> <aop:aspect id=" " ref=" "> </aop:aspect> </aop:config>
5.3.aop:xxx 标签
标签位置:aop:aspect标签内部
在aop:aspect标签的内部使用对应标签来配置通知的类型
在说以下通知类型:前置通知,后置通知。异常通知,最终通知
- aop:before:表示配置前置通知
- method属性:用于指定通知类中哪个方法是前置通知
- pointcut属性:用于指定切入点表达式,该表达式的含义指的是对哪些方法进行增强
- 联系起来就是:使用通知类中的那个方法,对待增强的方法进行增强,且增强的方法在待增强方法之前执行
切入点表达式的写法:
- 关键字:execution(表达式)
- 表达式:访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)
- 标准的表达式写法范例:
public void com.aismall.service.impl.AccountServiceImpl.saveAccount()
- 访问修饰符可以省略:
void com.aismall.service.impl.AccountServiceImpl.saveAccount()
- 返回值可以使用通配符*,表示任意返回值:
* com.aismall.service.impl.AccountServiceImpl.saveAccount()
- 包名可以使用通配符,表示任意包。但是有几级包,就需要写几个
*.
:* *.*.*.*.AccountServiceImpl.saveAccount())
- 包名可以使用
..
表示当前包及其子包:* *..AccountServiceImpl.saveAccount()
- 类名和方法名都可以使用
*
来实现通配:* *..*.*()
- 参数列表:
- 可以直接写数据类型:
- 基本类型直接写名称 :int
- 引用类型写包名.类名的方式 :java.lang.String
- 可以使用通配符表示任意类型,但是必须有参数
- 可以使用
..
表示有无参数均可,有参数可以是任意类型 - 全通配写法:
* *..*.*(..)
- 可以直接写数据类型:
实际开发中切入点表达式的通常写法,切到业务层实现类下的所有方法: * com.aismall.service.impl.*.*(..)
,例如:
<aop:config>
<!--配置切面 -->
<aop:aspect id=" " ref=" ">
<aop:before method=" " pointcut="execution(* com.aismall.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
- aop:after-returning:表示配置后置通知
- aop:after-throwing:表示配置异常通知
- aop:after :表示配置最终通知
- 注意:这几种通知里面的写法都是相同的,配置完之后通知出现的顺序不同。
5.4.aop:pointcut 标签
作用:结合aop:XXX
使用,简化配置
位置:可以再aop:aspect
标签内部使用,与aop:XXX
标签同级,这样就只当前切面可用也可以在aop:config
标签内使用,与aop:aspect
标签同级,这样aop:config
标签内的所有切面都可以使用,例如:
<!--配置AOP-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.aismall.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面 -->
<aop:aspect id="advice" ref="Advice">
<!-- 配置前置通知:在切入点方法执行之前执行-->
<aop:before method="beforeAdvice" pointcut-ref="pt1" ></aop:before>
<!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个-->
<aop:after-returning method="afterReturningAdvice" pointcut-ref="pt1"></aop:after-returning>
<!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个-->
<aop:after-throwing method="afterThrowingAdvice" pointcut-ref="pt1"></aop:after-throwing>
<!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行-->
<aop:after method="afterAdvice" pointcut-ref="pt1"></aop:after>
</aop:aspect>
</aop:config>
5.5.aop:around标签(环绕通知)
在spring的通知(Advice)中 一共有五种通知,之前已经介绍了四种,为什么不把环绕通知和他们放在一起说,因为环绕通知可以把前面的四种通知都表示出来,而且环绕通知一般单独使用。
环绕通知的使用:
- 环绕通知使用会出现的问题?:
- 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
- 分析:
- 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
- 解决:
- Spring框架为我们提供了一个接口:
ProceedingJoinPoint
。该接口有一个方法proceed()
,此方法就相当于明确调用切入点方法。
该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
- Spring框架为我们提供了一个接口:
- 注意:增强代码写在调用
proceed()
方法之前为前置通知,之后为后置通知,写在catch中为异常通知,写在finally中为最终通知
spring中的环绕通知:它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式,使用步骤如下:
- 1.先写通知类中内容
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("通知类中的aroundAdvice方法执行了。。前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("通知类中的aroundAdvice方法执行了。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("通知类中的aroundAdvice方法执行了。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("通知类中的aroundAdvice方法执行了。。最终");
}
}
- 2.在配置中配置环绕通知
<!--配置AOP-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.aismall.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面 -->
<aop:aspect id="aroundAdvice" ref="Advice">
<!-- 配置环绕通知 详细的注释请看Logger类中-->
<aop:around method="aroundAdvice" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
06.案例演示(基于XML)
演示spring中的AOP,具体看看spring是如何通过配置来实现动态代理的,在业务层演示如何通过配置的方式将业务代码进行增强。
6.1.新建一个maven项目(spring)
导入坐标
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
6.2.编写IAccountService接口和AccountServiceImpl.java实现类
IAccountService
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 模拟保存账户
*/
void saveAccount();
}
- AccountServiceImpl.java
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService{
@Override
public void saveAccount() {
System.out.println("执行了保存");
// int i=1/0;
}
}
6.3.编写工具类Advice(通知类)
/**
* 通知类,它里面提供了公共的代码
*/
public class Advice {
/**
* 前置通知
*/
public void beforeAdvice(){
System.out.println("前置通知Advice类中的beforeAdvice方法执行了。。。");
}
/**
* 后置通知
*/
public void afterReturningAdvice(){
System.out.println("后置通知Advice类中的afterReturningAdvice方法开执行了。。。");
}
/**
* 异常通知
*/
public void afterThrowingAdvice(){
System.out.println("异常通知Advice类中的afterThrowingAdvice方法执行了。。。");
}
/**
* 最终通知
*/
public void afterAdvice(){
System.out.println("最终通知Advice类中的afterAdvice方法执行了。。。");
}
/**
* 环绕通知
*/
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("通知类中的aroundAdvice方法执行了。。前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("通知类中的aroundAdvice方法执行了。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("通知类中的aroundAdvice方法执行了。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("通知类中的aroundAdvice方法执行了。。最终");
}
}
}
6.4.bean.xml
注意:此处要导入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">
<!-- 配置srping的Ioc,把service对象配置进来-->
<bean id="accountService" class="com.aismall.service.impl.AccountServiceImpl"></bean>
<!-- 配置advice通知类 -->
<bean id="advice" class="com.aismall.utils.Advice"></bean>
<!--配置AOP-->
<aop:config>
<!--为了使所有切面都可以使用,此标签配置在外面-->
<aop:pointcut id="pt1" expression="execution(* com.aismall.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面 -->
<aop:aspect id="advice" ref="advice">
<!-- 配置前置通知:在切入点方法执行之前执行-->
<aop:before method="beforeAdvice" pointcut-ref="pt1"></aop:before>
<!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个-->
<aop:after-returning method="afterReturningAdvice" pointcut-ref="pt1"></aop:after-returning>
<!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个-->
<aop:after-throwing method="afterThrowingAdvice" pointcut-ref="pt1"></aop:after-throwing>
<!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行-->
<aop:after method="afterAdvice" pointcut-ref="pt1"></aop:after>
<!-- 配置环绕通知-->
<!--<aop:around method="aroundAdvice" pointcut-ref="pt1"></aop:around>-->
</aop:aspect>
</aop:config>
</beans>
6.5.编写测试类AOPTest.java
/**
* 测试AOP的配置
*/
public class AOPTest {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountService as = (IAccountService)ac.getBean("accountService");
//3.执行方法
as.saveAccount();
}
}
6.6.运行结果
前置通知Advice类中的beforeAdvice方法执行了。。。
执行了保存
后置通知Advice类中的afterReturningAdvice方法开执行了。。。
最终通知Advice类中的afterAdvice方法执行了。。。
07.案例演示(基于注解)
- 案例的总体实现功能和上面那个案例是一样的,只不过是使用注解的方式
- 创建工程后需要导入的坐标,测试方法AOPTest.java和IAccount接口都和之前的一样。
在AccountServiceImpl.java中添加注解:@Service("accountService")
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService{
@Override
public void saveAccount() {
System.out.println("执行了保存");
//int i=1/0;
}
}
bean.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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.aismall"></context:component-scan>
<!-- 配置spring开启注解AOP的支持 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
通知类使用注解进行配置(重点)
/**
* 通知类,它里面提供了公共的代码
*/
@Component("advice")
@Aspect//表示当前类是一个切面类
public class Advice {
@Pointcut("execution(* com.aismall.service.impl.*.*(..))")
private void pt1(){}
/**
* 前置通知
*/
@Before("pt1()")
public void beforePrintLog(){
System.out.println("前置通知Advice类中的beforeAdvice方法执行了。。。");
}
/**
* 后置通知
*/
@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("后置通知Advice类中的afterReturningAdvice方法开执行了。。。");
}
/**
* 异常通知
*/
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("异常通知Advice类中的afterThrowingAdvice方法执行了。。。");
}
/**
* 最终通知
*/
@After("pt1()")
public void afterPrintLog(){
System.out.println("最终通知Advice类中的afterAdvice方法执行了。。。");
}
//@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("通知类中的aroundAdvice方法执行了。。前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("通知类中的aroundAdvice方法执行了。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("通知类中的aroundAdvice方法执行了。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("通知类中的aroundAdvice方法执行了。。最终");
}
}
}
08.AOP中使用基于注解和XML的注意事项
AOP中使用注解进行配置时选用:环绕通知
- 原因:使用(前置通知,后置通知,异常通知,最终通知)时,执行顺序有问题,先执行前置通知,然后执行最终通知,再执行后置通知或者异常通知
AOP中使用XML进行配置时选用环绕通知或者使用这一组通知(前置通知,后置通知,异常通知,最终通知)都可以,优先使用(前置通知,后置通知,异常通知,最终通知),因为简单。