简单的aop环绕通知的案例(自定义注解形式)

简单的aop环绕通知的案例(自定义注解形式),第1张

简单的aop环绕通知的案例(自定义注解形式)

自定义注解

@Target(ElementType.METHOD) //  表示注解的使用范围
@Retention(RetentionPolicy.RUNTIME) //  注解的声明周期
@documented
public @interface CheYuHang {

    //  定义前缀
    String prefix() default "cache";
}

切面类


@Component
@Aspect
public class LogAspect {

    @Around("@annotation(com.baizhi.springboot_jsp_shiro.test.aop.CheYuHang)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println("获取方法的名字"+method.getName());

        CheYuHang annotation = method.getAnnotation(CheYuHang.class);
        System.out.println("获取方法注解前缀"+annotation.prefix());

        System.out.println("获取方法的返回值类型"+method.getReturnType());

        Class[] parameterTypes = method.getParameterTypes();
        for (Class parameterType : parameterTypes) {
            System.out.println("获取方法的参数类型"+parameterType);
        }

        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            System.out.println("方法的参数值为"+arg);
        }
        return joinPoint.proceed(args);
    }
}

服务类

@Component
public class TestAop {

    @CheYuHang(prefix = "cache")
    public Integer test(int a,int b){
        System.out.println("testAop.....................");
        return a+b;
    }
}

控制层(controller)

 @GetMapping("/test")
    public void  test(){
        System.out.println("test.........");
        Integer test = testAop.test(1, 1);
        System.out.println("执行结果为"+test);
    }

执行结果

test.........
获取方法的名字test
获取方法注解前缀cache
获取方法的返回值类型class java.lang.Integer
获取方法的参数类型int
获取方法的参数类型int
方法的参数值为1
方法的参数值为1
testAop.....................
执行结果为2

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5434541.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存