ITPub博客

首页 > 数据库 > 数据库开发技术 > 自定义注解之AspectJ切面动态代理使用注意事项

自定义注解之AspectJ切面动态代理使用注意事项

原创 数据库开发技术 作者:Java大飞哥 时间:2025-01-14 21:42:46 0 删除 编辑

1.引入一下依赖

       <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>

2.自定义注解及切面

2.1自定义注解

@Target({ElementType.METHOD, ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface 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会自动开启。

@EnableAspectJAutoProxy(proxyTargetClass = true)

7.总结

通过这点东西,后面会写一篇文章分享,如何优雅自定义注解使用AspectJ切面及SpingBoot的Event机制记录业务接口调用日志及第三方接口调用日志,这个思路实现之后对于后期排查问题是非常的方便,本次分享到此结束,希望我的分享对你有所帮助,请一键三连,么么么哒!


原文作者:Java大飞哥;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2024-12-26

  • 博文量
    115
  • 访问量
    73139