Java注解

概述

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;
}

执行结果
在这里插入图片描述

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值