我脑子记不住的就索引这里

spring 自定义注解与AOP配合使用

自定义注解类

@Documented // 注解信息会被添加到Java文档中
@Retention(RetentionPolicy.RUNTIME) // 注解的生命周期,表示注解会被保留到什么阶段,可以选择编译阶段、类加载阶段,或运行阶段
@Target(ElementType.METHOD) // 注解作用的位置,ElementType.METHOD表示该注解仅能作用于方法上
public @interface ZiDingYi {
    
}

切面类

@Component // 让spring扫描到
@Aspect // 告诉spring这是个切面类
public class ZiDingYiAspect {

    /* 切点的类路径:填上面那个自定注解路径 */
    @Pointcut("@annotation(com.springboot.ZiDingYi)")
    private void pointcut() {}

    /* 方法前执行 */
    @Before("pointcut()")
    public void sayHello(){
        System.out.println("注解类型前置通知");
    }
    
    /* 方法后执行 */
    @After("pointcut()")
    public void sayGoodbey(){
        System.out.println("注解类型后置通知");
    }
    
    //环绕通知。注意要有ProceedingJoinPoint参数传入。
    @Around("pointcut()")
    public void sayAround(ProceedingJoinPoint joinPoint) throws Throwable{
    
        Object[] args = joinPoint.getArgs(); // 获取方法参数值数组
        
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();// 得到其方法签名
        
        Class[] paramTypeArray = methodSignature.getParameterTypes(); // 获取方法参数类型数组
        if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
            args[args.length - 1] = entityManager; // 如果方法的参数列表最后一个参数是entityManager类型,则给其赋值
        }
        logger.info("请求参数为{}",args);
        /*
         * 动态修改其参数
         * joinPoint.proceed(Object[] args),将刚刚修改的args参数传过去才算修改
         * joinPoint.proceed() 不修改参数的执行
         */
        Object result = joinPoint.proceed(args);
        logger.info("响应结果为{}",result);
        
        return result; // 如果这里不返回result,则目标对象实际返回值会被置为null

  }

}

------------------------------------------------------------------------

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容