注解(annotation)其實是一種接口,通過java的反射機制相關的API來訪問annotation信息。Java語言解釋器會在工作時忽略這些annotation,因此在JVM中這些annotation是不會被處理的,只能通過配套的工具才能對這些annotation類型的信息進行訪問和處理。
annotation的類型使用關鍵字@interface。它繼承了java.lang.annotation.Annotation接口,而不是申明了一個interface。
Annotation類型、方法定義是獨特的、受限制的。Annotation類型的方法必須申明為無參數、無異常拋出的。方法后面可以使用default和一個默認數值來申明成員的默認值,null不能作為成員的默認值。
元注解@Target,@Retention,@Documented,@Inherited
@Target表示該注解用於什么地方,@Retention表示在什么級別保存改注解信息,@Documented表示將此注解包含在javadoc中,@Inherited表示允許子類繼承父類中的注解。
注解示例:
1 @Target({ElementType.TYPE,ElementType.METHOD}) 2 @Retention(RetentionPolicy.RUNTIME) 3 public @interface NeedLogin{ 4 boolean value() default true; 5 boolean guest() default true; 6 }
解析注解:
1 if(handler instanceof HandlerMethod){ 2 HandlerMethod method = (HandlerMethod)handler; 3 NeedLogin needLogin = method.getMethodAnnotation(NeedLogin.class); 4 if(needLogin == null){ 5 needLogin = method.getMethod().getDeclaringClass().getAnnotation(NeedLogin.class); 7 } 8 }
注解本身不做任何事情,只是像xml文件一樣起到配置作用。注解代表的是某種業務意義,spring中@Resource注解簡單解析:首先解析類的所有屬性,判斷屬性上面是否存在這個注解,如果存在這個注解,再根據搜索規則來取得這個bean,然后通過反射注入。