Spring @RestController注解組合實(shí)現(xiàn)方法解析
Spring中存在很多注解組合的情況,例如@RestController
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic @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兩個(gè)注解的組合,同時(shí)產(chǎn)生兩個(gè)注解的作用。
本人一開(kāi)始以為這是Java的特性,Java能夠通過(guò)注解上的注解實(shí)現(xiàn)自動(dòng)組合注解的效果。于是寫(xiě)了這樣一段代碼
/** * @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)@MyComponentpublic @interface MyController {}
@MyControllerpublic class AnnotatedService {}
結(jié)果測(cè)試發(fā)現(xiàn)翻車
/** * @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); } }}
打印結(jié)果如下:
interface com.example.demo.anno.MyControllerfalse
經(jīng)過(guò)本人查閱資料,發(fā)現(xiàn)我想要的那個(gè)注解組合注解的功能是Spring自己實(shí)現(xiàn)的。。通過(guò)Spring中的AnnotationUtils.findAnnotation(類,注解)方法來(lái)判斷某個(gè)類上是否能找到組合的注解。
比如現(xiàn)在我想知道AnnotatedService這個(gè)類上是否存在@MyComponent注解,畢竟這是我一開(kāi)始的目的(通過(guò)組合減少注解),我可以調(diào)用一下代碼
/** * @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()
假如傳入的注解是一個(gè)不存在的值,則會(huì)返回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)); }}
控制臺(tái)打印:
null
總結(jié):Java本身沒(méi)有實(shí)現(xiàn) 通過(guò)標(biāo)記注解 來(lái)組合注解的功能。假如我們自定義注解時(shí)需要可以使用Spring的AnnotationUtils.findAnnotation()的方法幫助我們實(shí)現(xiàn)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP基礎(chǔ)知識(shí)Command對(duì)象講解2. 匹配模式 - XSL教程 - 43. ASP編碼必備的8條原則4. asp中response.write("中文")或者js中文亂碼問(wèn)題5. 詳解JS前端使用迭代器和生成器原理及示例6. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. 使用css實(shí)現(xiàn)全兼容tooltip提示框9. php bugs代碼審計(jì)基礎(chǔ)詳解10. ASP基礎(chǔ)入門(mén)第三篇(ASP腳本基礎(chǔ))
