获取注解中传递的参数

2020-01-09  本文已影响0人  陈柴盐

传统我们获取注解中的参数都是通过反射进行获取的,但是反射会带来性能消耗的问题,而且这部分反射的代码大多与逻辑无关,Spring其实提供了直接从注解中获取注解的方法。

获取注解上的参数

part1:定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DefineAnnotation {

  String value() default "";

}
part2.定义拦截器
@Aspect
@Slf4j
@Component
public class DefineInterceptorDouble {

    @Pointcut(value = "@annotation(defineAnnotation)")
    public void pointcut(DefineAnnotation defineAnnotation) {

    }

    @Around(value = "pointcut(defineAnnotation)")
    public void handler(DefineAnnotation defineAnnotation) {
        assert defineAnnotation.value().equals("annotation args");
    }
}

part3.使用注解
@Service
public class DefineService {

    @DefineAnnotation(value = "annotation args")
    public  String getDefineValue(String  param) {
        return param ;
    }

}

重点在拦截器的@annotation(defineAnnotation)上,网上的大多使用的是@annotation(注解类的全路径),只能单纯拦截使用该注解的方法,不能得到注解上面携带的参数,@annotation(defineAnnotation)可以根据defineAnnotation的类型进行拦截,本质跟@annotation(注解类的全路径)一样的。

获取拦截器的其他内容

AOP拦截器除了可以获取注解上的内容,还可以获取传入的参数以及调用拦截方法的实体

part1.定义注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DefineAnnotation {

   String value() default "";

}
part2.定义拦截器
@Aspect
@Slf4j
@Component
public class DefineInterceptor {

    @Pointcut(value = "@annotation(defineAnnotation)&&args(param) && target(bean)", argNames = "defineAnnotation,param, bean")
    public void pointcut(DefineAnnotation defineAnnotation,String param, DefineService bean ) {

    }

    @Around(value = "pointcut(defineAnnotation, param, bean )")
    public void handler(DefineAnnotation defineAnnotation,String param, DefineService bean) {
        assert  defineAnnotation.value().equals("annotation args");
        assert param.equals("input Arg1");
        assert null != bean;
    }
}
part3.使用注解
 @Test
    void contextLoads() {
        defineService.getDefineValue("input Arg1");
    }

跟案例1唯一的不同就是拦截器的使用不一样,引入了args和target来获取参数和执行类。

参考:http://loveshisong.cn/%E7%BC%96%E7%A8%8B%E6%8A%80%E6%9C%AF/2016-06-01-AOP%E4%B8%AD%E8%8E%B7%E5%8F%96%E6%96%B9%E6%B3%95%E4%B8%8A%E7%9A%84%E6%B3%A8%E8%A7%A3%E4%BF%A1%E6%81%AF.html

原创文章,转载请注明出处:https://www.jianshu.com/p/5e3d49947af4

上一篇 下一篇

猜你喜欢

热点阅读