传统我们获取注解中的参数都是通过反射进行获取的,但是反射会带来性能消耗的问题,而且这部分反射的代码大多与逻辑无关,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来获取参数和执行类。
原创文章,转载请注明出处:https://www.jianshu.com/p/5e3d49947af4
网友评论