Spring AOP
基于代理实现的日志
栗子:
一个计算器Calculator接口
public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
}
一个简单实现了该接口的类MyCalculator
public class MyCalculator implements Calculator {
@Override
public int add(int i, int j) {
int res = i+j;
return res;
}
@Override
public int sub(int i, int j) {
int res = i-j;
return res;
}
}
代理类
public class CalculatorProxy {
//需要代理的对象
private Calculator target;
public CalculatorProxy(Calculator target) {
this.target = target;
}
Calculator getCalculatorProxy() {
Calculator ans = null;
//表明哪一个类加载器负责加载
ClassLoader loader = target.getClass().getClassLoader();
//代理对象的类型,即其中有哪些方法
Class[] interfaces = new Class[] {Calculator.class};
//当代理对象调用其中的方法时,该执行的代码
InvocationHandler h = new InvocationHandler() {
/**
* proxy:正在返回的那个代理对象。
* 一般情况下,在invoke方法中都不使用该对象若调用,会出现死循环
* method:正在被调用的方法
* args:调用方法时,传入的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String name = method.getName();
//日志
System.out.println("Method " + name + " run with args:" + Arrays.toString(args));
//执行方法
Object result = method.invoke(target, args);
//日志
System.out.println("Method " + name + " run with result:" + result);
return result;
}
};
ans = (Calculator) Proxy.newProxyInstance(loader, interfaces, h);
return ans;
}
}
//用lambda表达式来改写上上面这段代码
public Calculator getCalculatorProxy() {
Calculator proxy = null;
proxy = (Calculator) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
new Class[] {Calculator.class},
(Object obejct, Method method, Object[] args) -> {
String name = method.getName();
//日志
System.out.println("Method " + name + " runs with args:" + Arrays.toString(args));
//执行方法
Object result = null;
result = method.invoke(target, args);
//日志
System.out.println("Method " + name + " runs with result:" + result);
return result;
});
return proxy;
}
AOP 术语
切面(
Aspect
): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象通知(
Advice
): 切面必须要完成的工作目标(
Target
): 被通知的对象代理(
Proxy
): 向目标对象应用通知之后创建的对象连接点(
Joinpoint
):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如ArithmethicCalculator#add()
方法执行前的连接点,执行点为ArithmethicCalculator#add()
; 方位为该方法执行前的位置切点(
Pointcut
):每个类都拥有多个连接点:例如ArithmethicCalculator
的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP
通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过org.springframework.aop.Pointcut
接口进行描述,它使用类和方法作为连接点的查询条件
基于注解的AOP
在 Spring
中启用 AspectJ
注解支持:
要在
Spring
应用中使用AspectJ
注解, 必须在classpath
下包含AspectJ
类库:aopalliance.jar
、aspectj.weaver.jar
和spring-aspects.jar
将
aop Schema
添加到<beans>
根元素中.要在
Spring IOC
容器中启用AspectJ
注解支持, 只要在Bean
配置文件中定义一个空的XML
元素<aop:aspectj-autoproxy>
当
Spring IOC
容器侦测到Bean
配置文件中的<aop:aspectj-autoproxy>
元素时, 会自动为与AspectJ
切面匹配的Bean
创建代理.
同时需要在XML文件中启用组件扫描和启用AspectJ注解,为匹配AspectJ注解的Java类自动生成代理类。
<!-- 启用包扫描 -->
<context:component-scan base-package="concert"></context:component-scan>
<!-- 启用AspectJ注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
用 AspectJ 注解声明切面:
要在
Spring
中声明AspectJ
切面, 只需要在IOC
容器中将切面声明为Bean
实例. 当在Spring IOC
容器中初始化AspectJ
切面之后,Spring IOC
容器就会为那些与AspectJ
切面相匹配的Bean
创建代理.在
AspectJ
注解中, 切面只是一个带有@Aspect
注解的Java
类.通知是标注有某种注解的简单的
Java
方法.
AspectJ
支持 5 种类型的通知注解:
@Before
:前置通知
- 前置通知:在方法执行之前执行的通知
- 前置通知使用
@Before
注解, 并将切入点表达式的值作为注解值.
@After
: 后置通知
- 后置通知是在连接点完成之后执行的,即连接点返回结果或者抛出异常的时候,下面的后置通知记录了方法的终止.
- 一个切面可以包括一个或者多个通知.
@AfterRunning
: 返回通知
- 无论连接点是正常返回还是抛出异常,后置通知都会执行.如果只想在连接点返回的时候记录日志,应使用返回通知代替后置通知.
- 在返回通知中, 只要将
returning
属性添加到@AfterReturning
注解中,就可以访问连接点的返回值.该属性的值即为用来传入返回值的参数名称. - 必须在通知方法的签名中添加一个同名参数.在运行时,
Spring AOP
会通过这个参数传递返回值.原始的切点表达式需要出现在pointcut
属性中
@AfterThrowing
:异常通知
- 只在连接点抛出异常时才执行异常通知
将
throwing
属性添加到@AfterThrowing
注解中,也可以访问连接点抛出的异常.Throwable
是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.
@Around
: 环绕通知
环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
对于环绕通知来说, 连接点的参数类型必须是
ProceedingJoinPoint
. 它是JoinPoint
的子接口, 允许控制何时执行, 是否执行连接点.在环绕通知中需要明确调用
ProceedingJoinPoint
的proceed()
方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用
joinPoint.proceed();
的返回值, 否则会出现空指针异常
try{
//@Before
method.invoke();
//@AfterRunning
} catch(Exception e) {
//@AfterThrowing
}
//@After
利用方法签名编写 AspectJ
切入点表达式
最典型的切入点表达式时根据方法的签名来匹配各种方法:
– execution * com.atguigu.spring.ArithmeticCalculator.*(..)
: 匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.
– execution public * ArithmeticCalculator.*(..)
: 匹配 ArithmeticCalculator 接口的所有公有方法.
– execution public double ArithmeticCalculator.*(..)
: 匹配 ArithmeticCalculator 中返回 double 类型数值的方法
– execution public double ArithmeticCalculator.*(double, ..)
: 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数
– execution public double ArithmeticCalculator.*(double, double)
: 匹配参数类型为 double, double 类型的方法.
基于AOP实现的日志
先看一个简单的栗子:
一场表演(接口):
//切点
public interface Performance {
void perform();
}
一个舞者(实现了表演接口):
@Component(value="dancer")
public class Dancer implements Performance {
@Override
public void perform() {
System.out.println("I'm a dancer and i'm dancing......");
}
}
一个切面:
//把该类声明为一个切面:需要把该类放入到IOC容器中,再声明为一个切面
//对于某位艺人的表演都会有观众的一系列动作
@Aspect
@Component
public class Audience {
//定义命名切点的名称
@Pointcut("execution(* concert.Performance.perform(..))")
public void perform() {}
//在表演之前发生
@Before("perform()")
public void slienceCellPhones() {
System.out.println("-->someone's phone is yelling...");
}
@Before("perform()")
public void takeSeats() {
System.out.println("-->Audiences take seats...");
}
//在表演之后发生
@After("perform()")
public void applause() {
System.out.println("-->Audiences applause....");
}
}
关键注解和重要的注释都在代码里。
测试代码及输出
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-concert.xml");
Performance dancer = (Performance)ctx.getBean("dancer");
dancer.perform();
}
//输出
-->someone's phone is yelling...
-->Audiences take seats...
I'm a dancer and i'm dancing......
-->Audiences applause....
再来看一个复杂一点的栗子:
一个计算器接口
public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
int div(int i, int j);
}
一个简单实现了该接口的类MyCalculator
@Component(value="calculator")
public class MyCalculator implements Calculator {
@Override
public int add(int i, int j) {
int res = i+j;
return res;
}
@Override
public int sub(int i, int j) {
int res = i-j;
return res;
}
@Override
public int div(int i, int j) {
int res = i/j;
return res;
}
}
切面
定义了前置通知,后置通知,返回通知,异常通知,环绕通知。
@Aspect
@Component
public class CalculatorAspect {
@Pointcut("execution(* spring.aop.Calculator.*(. .))")
public void method() {}
@Before("method()")
public void before(JoinPoint joinpoint) {
String name = joinpoint.getSignature().getName();
Object[] args = joinpoint.getArgs();
System.out.println("Method [ " + name + " ] runs with args: " + Arrays.toString(args));
}
@After(value="method()", argNames="")
public void after(JoinPoint joinpoint) {
String name = joinpoint.getSignature().getName();
System.out.println("Method [ " + name + " ] has invoked.");
}
@AfterReturning(pointcut="method()", returning="result")
public void afterReturning(JoinPoint joinpoint, Object result) {
String name = joinpoint.getSignature().getName();
System.out.println("Method [ " + name + " ] ends with result: " + result);
}
@AfterThrowing(pointcut="method()", throwing="ex")
public void afterThrowing(JoinPoint joinpoint, Exception ex) {
String name = joinpoint.getSignature().getName();
System.out.println("Method [ " + name + " ] occours with exception: " + ex);
}
@Around(value="method()")
public Object around(ProceedingJoinPoint pjd) {
String name = pjd.getSignature().getName();
Object res = -1;
try {
Object[] args = pjd.getArgs();
System.out.println("Method [ " + name + " ] runs with args: " + Arrays.toString(args));
res = pjd.proceed();
System.out.println("Method [ " + name + " ] ends with result: " + res);
} catch (Throwable e) {
System.out.println("Method [ " + name + " ] occours with exception: " + e);
}
System.out.println("Method [ " + name + " ] has ended.");
return res;
}
}
为了便于看出各个效果,单独测试环绕通知:
先看前四个通知:
前置通知,后置通知,返回通知,异常通知
Method [ add ] runs with args: [1, 2]
Method [ add ] has invoked.
Method [ add ] ends with result: 3
Result: 3
Method [ sub ] runs with args: [12, 2]
Method [ sub ] has invoked.
Method [ sub ] ends with result: 10
Result: 10
Method [ div ] runs with args: [1, 0]
Method [ div ] has invoked.
Method [ div ] occours with exception: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
......
......
环绕通知输出:
Method [ add ] runs with args: [1, 2]
Method [ add ] ends with result: 3
Method [ add ] has ended.
Result: 3
Method [ sub ] runs with args: [12, 2]
Method [ sub ] ends with result: 10
Method [ sub ] has ended.
Result: 10
Method [ div ] runs with args: [1, 0]
Method [ div ] occours with exception: java.lang.ArithmeticException: / by zero
Method [ div ] has ended.
Result: -1
指定切面的优先级
在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.
切面的优先级可以通过实现
Ordered
接口或利用@Order
注解指定.实现
Ordered
接口,getOrder()
方法的返回值越小, 优先级越高.
若使用 @Order
注解, 序号出现在注解中
@Aspect
@Order(0)
public class CalculatorValidationAspect{}
@Aspect
@Order(1)
public class CalculatorLoggingAspect{}
重用切入点定义
在编写
AspectJ
切面时, 可以直接在通知注解中书写切入点表达式. 但同一个切点表达式可能会在多个通知中重复出现.在
AspectJ
切面中, 可以通过@Pointcut
注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为
public
. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.其他通知可以通过方法名称引入该切入点.
@Pointcut("execution(* spring.aop.Calculator.*(. .))")
public void method() {}
基于XML文件配置实现的AOP
除了使用 AspectJ
注解声明切面, Spring
也支持在 Bean
配置文件中声明切面. 这种声明是通过 aop schema
中的 XML
元素完成的.
正常情况下, 基于注解的声明要优先于基于 XML
的声明. 通过 AspectJ
注解, 切面可以与 AspectJ
兼容, 而基于 XML
的配置则是 Spring
专有的. 由于 AspectJ
得到越来越多的 AOP
框架支持, 所以以注解风格编写的切面将会有更多重用的机会.
当使用 XML
声明切面时, 需要在 <beans>
根元素中导入 aop Schema
在 Bean
配置文件中, 所有的 Spring AOP
配置都必须定义在 <aop:config>
元素内部. 对于每个切面而言, 都要创建一个 <aop:aspect>
元素来为具体的切面实现引用后端 Bean
实例.
切面 Bean
必须有一个标示符, 供 <aop:aspect>
元素引用
声明切点表达式
切入点使用 <aop:pointcut>
元素声明
切入点必须定义在 <aop:aspect>
元素下, 或者直接定义在 <aop:config>
元素下.
定义在 <aop:aspect>
元素下: 只对当前切面有效
定义在 <aop:config>
元素下: 对所有切面都有效
基于 XML
的 AOP
配置不允许在切入点表达式中用名称引用其他切入点.
声明通知
在 aop Schema
中, 每种通知类型都对应一个特定的 XML 元素.
通知元素需要使用 <pointcut-ref>
来引用切入点, 或用 <pointcut>
直接嵌入切入点表达式. method
属性指定切面类中通知方法的名称.
<!-- 配置Bean,不能配置interface -->
<bean id="calculator" class="spring.aop.xml.MyCalculator"></bean>
<!-- 配置切面Bean -->
<bean id="calculatorAspect" class="spring.aop.xml.CalculatorAspect"></bean>
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* spring.aop.xml.Calculator.*(..))" id="pointcut"/>
<!-- 配置连接点 -->
<aop:aspect ref="calculatorAspect" order="2">
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>
<!-- 配置环绕通知
<aop:around method="around" pointcut-ref="pointcut"/>
-->
</aop:aspect>
</aop:config>
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aop-xml.xml");
Calculator cal = (Calculator) ctx.getBean("calculator");
System.out.println("Result: " + cal.add(1, 2));
System.out.println("Result: " + cal.sub(12, 2));
System.out.println("Result: " + cal.div(10, 0));
Method [ add ] runs with args: [1, 2]
Method [ add ] has invoked.
Method [ add ] ends with result: 3
Result: 3
Method [ sub ] runs with args: [12, 2]
Method [ sub ] has invoked.
Method [ sub ] ends with result: 10
Result: 10
Method [ div ] runs with args: [10, 0]
Method [ div ] has invoked.
Method [ div ] occours with exception: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException:
同上
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* spring.aop.xml.Calculator.*(..))" id="pointcut"/>
<!-- 配置连接点 -->
<aop:aspect ref="calculatorAspect" order="2">
<!-- 配置通知 -->
<aop:around method="around" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
Method [ add ] runs with args: [1, 2]
Method [ add ] ends with result: 3
Method [ add ] has ended.
Result: 3
Method [ sub ] runs with args: [12, 2]
Method [ sub ] ends with result: 10
Method [ sub ] has ended.
Result: 10
Method [ div ] runs with args: [10, 0]
Method [ div ] occours with exception: java.lang.ArithmeticException: / by zero
Method [ div ] has ended.
Result: -1