
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.9.4</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.6</version></dependency>
public xxxRequestLogAnno {}
@Slf4j@Aspect@Componentpublic class xxxxRequestLogAspect {//切面表达式写法还有很多种@Pointcut("@annotation(xxxx.xxxx.xxxx.annotation.xxxxRequestLogAnno)")public void xxxxRequestLogPoint() {}@Around("xxxxRequestLogPoint()")public xxxResp deal(ProceedingJoinPoint pjp) throws Throwable {//之前逻辑xxxResp result = null;try {result = pjp.proceed();}catch (Exception e){//异常逻辑}//之后逻辑return result;}}
在主启动类上@ComponentScan("com.example.demo.*")扫码包路径需要包含切面的包路径
@Aspect@Component
自定义注解加在方法的类必须让springBoot的容器管理(必须是spirng容器的bean,所以自定义注解标记的方法的类上使@Service等spring的注解)这种目标类才是一个bean。自定义注解标记的方法不能是private修饰的。
在主启动类上添加如下注解,这一步不是必须的,可以不加,不加也springBoot也是会自动装配的,如果没有加aop-starter需要加这个手动开启,加了aop-start会自动开启。
(proxyTargetClass = true)通过这点东西,后面会写一篇文章分享,如何优雅自定义注解使用AspectJ切面及SpingBoot的Event机制记录业务接口调用日志及第三方接口调用日志,这个思路实现之后对于后期排查问题是非常的方便,本次分享到此结束,希望我的分享对你有所帮助,请一键三连,么么么哒!
原文作者:Java大飞哥;如有侵权,请联系管理员删除。