Spring学习笔记02-面向切面编程AOP
原创
©著作权归作者所有:来自51CTO博客作者luer9的原创作品,请联系作者获取转载授权,否则将追究法律责任
Spring
文章目录
- 基于接口的动态代理
- 基于子类的动态代理
解决冗余:动态代理
- 特点:字节码随用随创建,随用随加载
- 作用:不修改源码的基础上对方法增强
- 分类:
基于接口的动态代理
- 涉及的类:proxy
- 提供者:jdk
- 创建代理对象:使用Proxy类中的
newProxyInstance
方法 - 创建代理对象的要求:被代理类最少实现一个接口,如果没有则不能被使用
-
newProxyInstance
方法参数
- 用于加载代理对象字节码的,和被代理对象使用相同的类加载器 , 固定写法
-
InvocationHandler
:用于提供增强的代码
- 让我们写如何代理,一般都是些接口的实现类,通常情况下为匿名内部类,但不是必须的。此接口的实现类是谁用谁写
IProducer proxyProducer =(IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(),producer.getClass().getInterfaces(),new InvocationHandler(){
/**
* 作用:执行被代理对象的任何接口方法都会经过该方法
* @param proxy 代理对象的引用
* @param method 当前执行的方法
* @param args 当前执行方法所需的参数
* @return 和被代理对象方法有相同的返回值
* @throws Throwable
* */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float)args[0];
//2.判断当前方法是不是销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
模板
接口名 新对象名 = (接口名)Proxy.newProxyInstance(
被代理的对象.getClass().getClassLoader(), // 被代理对象的类加载器,固定写法
被代理的对象.getClass().getInterfaces(), // 被代理对象实现的所有接口,固定写法
new InvocationHandler() { // 匿名内部类,通过拦截被代理对象的方法来增强被代理对象
/* 被代理对象的任何方法执行时,都会被此方法拦截到
其参数如下:
proxy: 代理对象的引用,不一定每次都用得到
method: 被拦截到的方法对象
args: 被拦截到的方法对象的参数
返回值:
被增强后的返回值
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("方法名".equals(method.getName())) {
// 增强方法的操作
rtValue = method.invoke(被代理的对象, args);
// 增强方法的操作
return rtValue;
}
}
});
基于子类的动态代理
- 涉及的类:Enhancer
- 提供者:第三方cglib
- 创建代理对象:使用Enhancer类中的
create
方法 - 创建代理对象的要求:被代理类不能是最终类
-
create
方法的参数
- 让我们写如何代理,一般都是些接口的实现类,通常情况下为匿名内部类,但不是必须的。此接口的实现类是谁用谁写。我们一般写的都是该接口的子接口实现类
MethodIntercepter
Producer cglibProducer =(Producer)Enhancer.create(producer.getClass(), new MethodInterceptor() {
/**
* 执行被代理对象的任何方法都会经过该方法
* @param method
* @param proxy
* @param args
* 以上三个参数和基于接口的动态代理中的invoke方法的参数是一样的
* @param methodProxy :当前执行方法的代理对象
* @return
* @throws Throwable
* */
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float)args[0];
//2.判断当前方法是不是销售
if("saleProduct".equals(method.getName())){
returnValue = method.invoke(producer,money*0.8f);
}
return returnValue;
}
});
cglibProducer.saleProduct(12000f);
使用Spring的AOP解决代码冗余
AOP相关术语
- Joinpoint(连接点): 被拦截到的方法.
- Pointcut(切入点): 我们对其进行增强的方法.
- Advice(通知/增强): 对切入点进行的增强操作
包括前置通知,后置通知,异常通知,最终通知,环绕通知 - Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。
- Aspect(切面): 是切入点和通知的结合
spring中基于xml的AOP
步骤
- 把通知的Bean也交给spring来管理
- 使用
aop:config
标签表明开始配置AOP配置 - 使用
aop:aspect
标签表明配置切面
id
:给切面提供一个唯一标识
ref
:指定通知类bean的id - 在
aop:aspect
标签内部使用对应标签来配置通知的类型
我们现在示例是让printLog
方法在切入点方法执行之前执行,所以是前置通知
aop:before
:表示配置前置通知
method
属性用于指定Logger类
中哪个方法是前置通知
pointcut
属性用于指定切入点表达式,该表达式的含义是指对业务层中哪些方法增强
切入点表达式的写法
- 关键字:execution(表达式)
- 表达式:
访问修饰符 返回值 包名.包名…类名.方法名(参数列表) - 标准表达式写法
public void com.yll.service.impl.AccountServiceImpl.saveAccount()
** 访问修饰符可以省略 **
void com.yll.service.impl.AccountServiceImpl.saveAccount()
- 返回值可以使用通配符,表示任意返回值
* com.yll.service.impl.AccountServiceImpl.saveAccount()
- 包名可以使用通配符,表示任意包。有几级包,就需要写几个*.
* *.*.*.*.AccountServiceImpl.saveAccount()
- 包名可以使用…表示当前包及其子包
* *..AccountServiceImpl.saveAccount()
- 类名和方法名都可以使用*表示统配
* *..*.*()
- 参数列表:
可以直接写数据类型
基本类型直接写名称 int
引用类型写包名.类名的方式 java.lang.String
可以使用通配符*表示任意类型 但是必须有参数
可以使用…表示有无参数均可,有参数可以是任意类型 - 全通配写法:
* *..*.*(..)
实际开发中切入点表达式的通常写法:切到业务层实现类下的所有方法:
* com.yll.service.impl.*.*(..)
<?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">
<!--配置spring的ioc,把service对象配置进来-->
<bean id="accountService" class="com.yll.service.impl.AccountServiceImpl" />
<!--配置logger类-->
<bean id="logger" class="com.yll.utils.Logger"></bean>
<!--配置aop-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.yll.service.impl.AccountServiceImpl.saveAccount())"/>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置通知类型,并且建立通知方法和切入点方法的关联-->
<!--前置通知:在切入点方法执行之前执行-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
<!--后置通知:在切入点方法正常执行之后执行-->
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
<!--异常通知:在切入点方法执行产生异常之后执行-->
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
<!--最终通知:无论切入点方法是否正常执行它都会在其后面执行-->
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
<!--配置环绕通知-->
<!-- <aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>-->
</aop:aspect>
<!--配置切入点表达式
id属性:用于指定表达式的唯一标志
expression:指定表达式内容
此标签写在aop:aspect标签内部只能当前切面使用
它还可以写在aop:aspect外边,此时就变成了所有切面可用,必须移动到切面之前
-->
</aop:config>
环绕通知
- 问题:当我们配置了环绕通知之后,切入点方法没有执行,通知方法执行了
- 分析:通过对比动态代理的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们没有
- 解决:spring框架为我们提供了一个接口:
ProceedingJoinPoint
,该接口有个方法proceed
,此方法相当于明确调用切入点方法 - 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
- spring中的环绕通知: 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
ProceedingJoinPoint对象的getArgs()方法返回被拦截的参数
ProceedingJoinPoint对象的proceed()方法执行被拦截的方法
模板
// 环绕通知方法,返回Object类型
public Object printLogAround(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
Object[] args = pjp.getArgs();
printLogBefore(); // 执行前置通知
rtValue = pjp.proceed(args);// 执行被拦截方法
printLogAfterReturn(); // 执行后置通知
}catch(Throwable e) {
printLogAfterThrowing(); // 执行异常通知
}finally {
printLogAfter(); // 执行最终通知
}
return rtValue;
}
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtnVal = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..前置");
rtnVal = pjp.proceed(args);//明确调用业务层(切入点)方法
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..后置");
return rtnVal;
}catch (Throwable t){
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..最终");
}
}
使用注解配置AOP
@Component("looger")
@Aspect //表示当前类是个切面类
public class Logger {
}
-
@Before
: 声明该方法为前置通知.相当于xml配置中的<aop:before>
标签 -
@AfterReturning
: 声明该方法为后置通知.相当于xml配置中的<aop:after-returning>
标签 -
@AfterThrowing
: 声明该方法为异常通知.相当于xml配置中的<aop:after-throwing>
标签 -
@After
: 声明该方法为最终通知.相当于xml配置中的<aop:after>
标签 -
@Around
: 声明该方法为环绕通知.相当于xml配置中的<aop:around>
标签 - 属性:
-
value
: 用于指定切入点表达式或切入点表达式的引用
-
@Pointcut
: 指定切入点表达式,其属性如下:
-
value
: 指定表达式的内容 -
@Pointcut
注解没有id属性,通过调用被注解的方法获取切入点表达式.
package com.yll.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 用于记录日志的工具类,提供了公共的代码
* */
@Component("looger")
@Aspect //表示当前类是个切面类
public class Logger {
@Pointcut("execution(* com.yll.service.impl.AccountServiceImpl.saveAccount())")
private void pt1(){}
/**
* 用于打印日志,计划让其在切入点方法执行之前执行
* (切入点方法就是业务层方法)
* */
/**
* 前置通知
* */
@Before("pt1()")
public void beforePrintLog(){
System.out.println("Logger类中的beforePrintLog方法开始记录日志了");
}
/**
* 后置通知
* */
@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("Logger类中的afterReturningPrintLog方法开始记录日志了");
}
/**
* 异常通知
* */
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("Logger类中的afterThrowingPrintLog方法开始记录日志了");
}
/**
* 最终通知
* */
@After("pt1()")
public void afterPrintLog(){
System.out.println("Logger类中的afterPrintLog方法开始记录日志了");
}
/**
* 环绕通知
* 问题:当我们配置了环绕通知之后,切入点方法没有执行,通知方法执行了
* 分析:通过对比动态代理的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们没有
* 解决:
* spring框架为我们提供了一个接口:ProceedingJoinPoint,该接口有个方法proceed,此方法相当于明确调用切入点方法
* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
* spring中的环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
* */
// @Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtnVal = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..前置");
rtnVal = pjp.proceed(args);//明确调用业务层(切入点)方法
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..后置");
return rtnVal;
}catch (Throwable t){
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志了..最终");
}
}
}
- 半注解配置AOP,需要在
bean.xml
中加入下面语句开启对注解AOP的支持
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 纯注解配置AOP,在Spring配置类前添加
@EnableAspectJAutoProxy
注解,可以使用纯注解方式配置AOP
@Configuration
@ComponentScan(basePackages="com.yll")
@EnableAspectJAutoProxy // 允许AOP
public class SpringConfiguration {
// 具体配置
//...
}
注意
使用注解配置AOP时,四个通知的调用顺序依次是:前置通知
,最终通知
,后置通知
. 这会导致一些资源在执行最终通知
时提前被释放掉了,而执行后置通知
时就会出错.