
1.引入一下依赖
<dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-aopartifactId>dependency><dependency><groupId>org.aspectjgroupId><artifactId>aspectjrtartifactId><version>1.9.4version>dependency><dependency><groupId>org.aspectjgroupId><artifactId>aspectjweaverartifactId><version>1.9.6version>dependency>
2.自定义注解及切面
2.1自定义注解
public xxxRequestLogAnno {}
2.2自定义切面
@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;}}
3.@ComponentScan扫到切面类
在主启动类上@ComponentScan("com.example.demo.*")扫码包路径需要包含切面的包路径
4.切面类加上如下注解
@Aspect@Component
5.目标类必须是一个bean及自定义注解标记的方法不能是private修饰
自定义注解加在方法的类必须让springBoot的容器管理(必须是spirng容器的bean,所以自定义注解标记的方法的类上使@Service等spring的注解)这种目标类才是一个bean。自定义注解标记的方法不能是private修饰的。
6.手动开启@EnableAspectJAutoProxy注解(非必须)
在主启动类上添加如下注解,这一步不是必须的,可以不加,不加也springBoot也是会自动装配的,如果没有加aop-starter需要加这个手动开启,加了aop-start会自动开启。
(proxyTargetClass = true)7.总结
通过这点东西,后面会写一篇文章分享,如何优雅自定义注解使用AspectJ切面及SpingBoot的Event机制记录业务接口调用日志及第三方接口调用日志,这个思路实现之后对于后期排查问题是非常的方便,本次分享到此结束,希望我的分享对你有所帮助,请一键三连,么么么哒!