网上都是说springboot使用Aspectj做面向切面编程的时候,只需要引入下面jar包依赖即可
org.springframework.boot
spring-boot-starter-aop
但是我去编写的时候,单单引入 spring-boot-starter-aop 的jar依赖的时候,像@Component、@Aspect等這些註解都不能使用,後來發現缺少aspectjweaver 这么个jar包,最后引入了下面的jar才解決問題
aspectj
aspectjweaver
1.5.3
网上也有说要在application.properties中添加spring.aop.auto=true这个配置,才能开启Aspectj注解的扫面,但是我去查询了springboot全局配置文件,里面默认配置为true(spring.aop.auto=true # Add @EnableAspectJAutoProxy),所以我没有去做添加,功能没有问题,切面能正常实现。
4)@AfterThrowing: 异常通知, 在方法抛出异常之后
5) @Around: 环绕通知, 围绕着方法执行(即方法前后都有执行)
环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
下面是我写的一些通知的实例,大家可以参考一下
/*
标识这个方法是个前置通知, 切点表达式表示执行任意类的任意方法.
第一个 * 代表匹配任意修饰符及任意返回值,
第二个 * 代表任意类的对象,
第三个 * 代表任意方法,
参数列表中的 .. 匹配任意数量的参数
*/
//@Before: 前置通知
@Before("execution (* com.lc.project..controller..*.*(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().toString();
Object result= Arrays.asList(joinPoint.getArgs());
System.out.println("The method name:"+methodName+"--value:"+result);
}
//@After: 后置通知
@After("execution (* *.*(..))")
public void afterMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method name:"+methodName+ " ends");
}
//@AfterRunning: 返回通知
@AfterReturning(value="execution (* *.*(..))",returning="result")
public void afterReturningMethod(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method name:"+methodName+ " ends and result="+result);
}
//@AfterThrowing: 异常通知
@AfterThrowing(value="execution (* *.*(..))",throwing="e")
public void afterReturningMethod(JoinPoint joinPoint,Exception e){
String methodName = joinPoint.getSignature().getName();
System.out.println("The method name:"+methodName+ " ends and result="+e);
}