栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring @RestController注解组合实现方法解析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring @RestController注解组合实现方法解析

Spring中存在很多注解组合的情况,例如@RestController

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
@Controller
@ResponseBody
public @interface RestController {

	
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

@RestController就是@Controller、@ResponseBody两个注解的组合,同时产生两个注解的作用。

本人一开始以为这是Java的特性,Java能够通过注解上的注解实现自动组合注解的效果。于是写了这样一段代码


@documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyComponent {
}

@documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@MyComponent
public @interface MyController {
}
@MyController
public class AnnotatedService {
}

结果测试发现翻车


public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    for (Annotation anno : annotations) {
      System.out.println(anno.annotationType());
      System.out.println(anno.annotationType() == MyComponent.class);
    }
  }
}

打印结果如下:

interface com.example.demo.anno.MyController
false

经过本人查阅资料,发现我想要的那个注解组合注解的功能是Spring自己实现的。。通过Spring中的AnnotationUtils.findAnnotation(类,注解)方法来判断某个类上是否能找到组合的注解。

比如现在我想知道AnnotatedService这个类上是否存在@MyComponent注解,毕竟这是我一开始的目的(通过组合减少注解),我可以调用一下代码


public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    System.out.println(AnnotationUtils.findAnnotation(AnnotatedService.class, MyComponent.class));
  }
}

打印如下:

@com.example.demo.anno.MyComponent()

假如传入的注解是一个不存在的值,则会返回null,示例如下:


public class Test {

  public static void main(String[] args) {
    Annotation[] annotations = AnnotatedService.class.getAnnotations();
    System.out.println(AnnotationUtils.findAnnotation(AnnotatedService.class, OtherAnno.class));
  }
}

控制台打印:

null

总结:Java本身没有实现 通过标记注解 来组合注解的功能。假如我们自定义注解时需要可以使用Spring的AnnotationUtils.findAnnotation()的方法帮助我们实现。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133527.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号