接着上一篇博客,这里主要记录一下各种增强的实现,包括前置增强,后置增强,环绕增强,异常抛出增强,引介增强,用@AspectJ来实现(需要注意的一个问题,jdk版本必须在1.5以上)
1.前置增强,业务层和aop拦截代码如下
package com.mimoprint.schedule.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class AopService {
public void testAop(){
log.info("******测试aop******");
}
}
package com.mimoprint.schedule.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Slf4j
@Component
public class AdviceAspect {
@Before("execution(* testAop(..))")
public void greetTo(){
log.info("=====前置增强=====");
}
}
结果:
注意aop上面必须有一个@Component注解,不然spring无法读取到这个bean,就没办法前置拦截了。
2.后置增强
@AfterReturning("execution(* testAop(..))")
public void after(){
log.info("=====后置增强=====");
}
3.环绕增强
@Around("execution(* testAop(..))")
public void around(ProceedingJoinPoint joinPoint){
log.info("=====环绕增强开始=====");
try {
joinPoint.proceed();
} catch (Throwable throwable) {
log.error("catch exception",throwable);
}
log.info("=====环绕增强结束=====");
}
注意这里引入一个ProceedingJoinPoint对象,里面封装了一些关于切面的使用方法,但是这个对象只在环绕注解中生效
4.异常抛出异常
@AfterThrowing("execution(* testAop(..))")
public void afterThrowing(){
log.info("=====抛出异常增强=====");
}
还有一种是引介增强,但是我也不怎么使用,这里就不在去记录了,有空的时候去找一下具体的用法,说不定以后能用到呢,哈哈。