歡迎您光臨本站 註冊首頁

Spring @RestController註解組合實現方法解析

←手機掃碼閱讀     sl_ivan @ 2020-06-29 , reply:0

Spring中存在很多註解組合的情況,例如@RestController

  @Target(ElementType.TYPE)  @Retention(RetentionPolicy.RUNTIME)  @Documented  @Controller  @ResponseBody  public @interface RestController {    	/**  	 * The value may indicate a suggestion for a logical component name,  	 * to be turned into a Spring bean in case of an autodetected component.  	 * @return the suggested component name, if any (or empty String otherwise)  	 * @since 4.0.1  	 */  	@AliasFor(annotation = Controller.class)  	String value() default "";    }

 

@RestController就是@Controller、@ResponseBody兩個註解的組合,同時產生兩個註解的作用。
 

本人一開始以為這是Java的特性,Java能夠通過註解上的註解實現自動組合註解的效果。於是寫了這樣一段代碼

  /**   * @author Fcb   * @date 2020/6/23   * @description   */  @Documented  @Target(ElementType.TYPE)  @Retention(RetentionPolicy.RUNTIME)  public @interface MyComponent {  }

 

  /**   * @author Fcb   * @date 2020/6/23   * @description   */  @Documented  @Target(ElementType.TYPE)  @Retention(RetentionPolicy.RUNTIME)  @MyComponent  public @interface MyController {  }

 

  @MyController  public class AnnotatedService {  }

 

結果測試發現翻車

  /**   * @author Fcb   * @date 2020/6/23   * @description   */  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註解,畢竟這是我一開始的目的(通過組合減少註解),我可以調用一下代碼

  /**   * @author Fcb   * @date 2020/6/23   * @description   */  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,示例如下:

  /**   * @author Fcb   * @date 2020/6/23   * @description   */  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()的方法幫助我們實現。

                                                       

   


[sl_ivan ] Spring @RestController註解組合實現方法解析已經有254次圍觀

http://coctec.com/docs/java/show-post-240293.html