概述
Java 注解(Annotation)是一种元数据形式,提供了在代码中添加标记、标识和说明的功能。注解本身不会影响程序的实际运行,但可以被编译器、开发工具和框架等程序所使用。
简单说,就是打标记,然后扫描标记,最后通过反射的方式去执行逻辑。
定义注解
用关键字@interface来定义注解,和定义类、接口的class、interface一样
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "";
int count() default 1;
}
@Retention和@Target是元注解,即用于修饰其他注解的注解
@Retention 注解表示该注解在程序运行时可以被反射读取,而 @Target 注解则指定了该注解可以作用于类级别上的 Java 元素
注解逻辑
通过拦截器去检查是否带有注解,并在拦截器中写带有注解时的执行逻辑。我的逻辑是输出带有该注解的方法的入参。
@Component
@Slf4j
public class AnnotationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Method method = ((HandlerMethod) handler).getMethod();
if (method.isAnnotationPresent(MyAnnotation.class)) {
String queryString = request.getQueryString();
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
log.info("自定义注解参数value:{}", myAnnotation.value());
log.info("自定义注解参数count:{}", myAnnotation.count());
log.info("自定义注解拦截器,入参:{}", queryString);
}
return true;
}
}
在 Spring Boot 的配置类(如 WebMvcConfigurer)中注册 AnnotationInterceptor 拦截器,使其生效。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private AnnotationInterceptor annotationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(annotationInterceptor);
}
}
应用注解
我在Controller中写了一个方法,方法上使用了注解@MyAnnotation
@MyAnnotation(value = "test123124", count = 10)
@GetMapping("testAnnotation")
public String testAnnotation(String param){
return param;
}
执行结果