spring aspect和spring advisor

spring声明切面
spring aspect和spring advisor区别

在面向切面编程时,我们一般会用<aop:aspect>,<aop:aspect>定义切面(包括通知(前置通知,后置通知,返回通知等等)和切点(pointcut))

在进行事务管理时,我们一般会用<aop:advisor>,<aop:advisor>定义通知其(通知器跟切面一样,也包括通知和切点)。

<aop:advisor>大多用于事务管理。
<aop:aspect>大多用于日志、缓存。

用<aop:advisor>配置切面的话也可以配置,但切面类跟aspect有所不同,需要实现接口,比如:

 1 package com.example.aop;
 2 
 3 import org.springframework.aop.AfterAdvice;
 4 import org.springframework.aop.AfterReturningAdvice;
 5 import org.springframework.aop.MethodBeforeAdvice;
 6 import org.springframework.aop.aspectj.AspectJAfterThrowingAdvice;
 7 import org.springframework.stereotype.Component;
 8 
 9 import java.lang.reflect.Method;
10 
11 @Component
12 public class SysAdvisor implements MethodBeforeAdvice,AfterAdvice,AfterReturningAdvice {
13 
14     public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
15         System.out.println(method.getName()+"刷拉完毕");
16     }
17 
18 
19     public void before(Method method, Object[] args, Object target) throws Throwable {
20         System.out.println(method.getName()+"一大刷拉");
21     }
22 }
View Code

这里实现了前置通知和返回通知接口。然后在配置文件中跟<aop:aspect>类似

<aop:config>
        <aop:pointcut id="pointcut" expression="execution(public * com.example.controller.*Controller.*(..))"/>
        <aop:advisor advice-ref="sysAdvisor" pointcut-ref="pointcut"/>
 </aop:config>

定义切点和切面类即可。不用像aspect那样定义通知。但大多数使用<aop:advisor>都是用于事务管理。

转自:https://www.cnblogs.com/qinglangyijiu/p/8430144.html

原文地址:https://www.cnblogs.com/shuaishuai1993/p/9358675.html