原文出自:http://blog.csdn.net/yjclsx/article/details/52101922
一、基礎知識:元注解
要深入學習注解,我們就必須能定義自己的注解,並使用注解,在定義自己的注解之前,我們就必須要了解Java為我們提供的元注解和相關定義注解的語法。
元注解:
元注解的作用就是負責注解其他注解。Java5.0定義了4個標准的meta-annotation類型,它們被用來提供對其它 annotation類型作說明。Java5.0定義的元注解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
這些類型和它們所支持的類在java.lang.annotation包中可以找到。下面我們看一下每個元注解的作用和相應分參數的使用說明。
@Target:
@Target說明了Annotation所修飾的對象范圍:Annotation可被用於 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。
作用:用於描述注解的使用范圍(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用於描述構造器
2.FIELD:用於描述域
3.LOCAL_VARIABLE:用於描述局部變量
4.METHOD:用於描述方法
5.PACKAGE:用於描述包
6.PARAMETER:用於描述參數
7.TYPE:用於描述類、接口(包括注解類型) 或enum聲明
使用實例:
@Target(ElementType.TYPE) public @interface Table { /** * 數據表名稱注解,默認值為類名稱 * @return */ public String tableName() default "className"; } @Target(ElementType.FIELD) public @interface NoDBColumn { }
注解Table 可以用於注解類、接口(包括注解類型) 或enum聲明,而注解NoDBColumn僅可用於注解類的成員變量。
@Retention:
@Retention定義了該Annotation被保留的時間長短:某些Annotation僅出現在源代碼中,而被編譯器丟棄;而另一些卻被編譯在class文件中;編譯在class文件中的Annotation可能會被虛擬機忽略,而另一些在class被裝載時將被讀取(請注意並不影響class的執行,因為Annotation與class在使用上是被分離的)。使用這個meta-Annotation可以對 Annotation的“生命周期”限制。
作用:表示需要在什么級別保存該注釋信息,用於描述注解的生命周期(即:被描述的注解在什么范圍內有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在運行時有效(即運行時保留)
Retention meta-annotation類型有唯一的value作為成員,它的取值來自java.lang.annotation.RetentionPolicy的枚舉類型值。具體實例如下:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Column { public String name() default "fieldName"; public String setFuncName() default "setField"; public String getFuncName() default "getField"; public boolean defaultDBValue() default false; }
Column注解的的RetentionPolicy的屬性值是RUTIME,這樣注解處理器可以通過反射,獲取到該注解的屬性值,從而去做一些運行時的邏輯處理
@Documented:
@Documented用於描述其它類型的annotation應該被作為被標注的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化。Documented是一個標記注解,沒有成員。
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Column { public String name() default "fieldName"; public String setFuncName() default "setField"; public String getFuncName() default "getField"; public boolean defaultDBValue() default false; }
@Inherited:
@Inherited 元注解是一個標記注解,@Inherited闡述了某個被標注的類型是被繼承的。如果一個使用了@Inherited修飾的annotation類型被用於一個class,則這個annotation將被用於該class的子類。
注意:@Inherited annotation類型是被標注過的class的子類所繼承。類並不從它所實現的接口繼承annotation,方法並不從它所重載的方法繼承annotation。
當@Inherited annotation類型標注的annotation的Retention是RetentionPolicy.RUNTIME,則反射API增強了這種繼承性。如果我們使用java.lang.reflect去查詢一個@Inherited annotation類型的annotation時,反射代碼檢查將展開工作:檢查class和其父類,直到發現指定的annotation類型被發現,或者到達類繼承結構的頂層。
實例代碼:
/** * * @author peida * */ @Inherited public @interface Greeting { public enum FontColor{ BULE,RED,GREEN}; String name(); FontColor fontColor() default FontColor.GREEN; }
二、基礎知識:自定義注解
使用@interface自定義注解時,自動繼承了java.lang.annotation.Annotation接口,由編譯程序自動完成其他細節。在定義注解時,不能繼承其他的注解或接口。@interface用來聲明一個注解,其中的每一個方法實際上是聲明了一個配置參數。方法的名稱就是參數的名稱,返回值類型就是參數的類型(返回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數的默認值。
定義注解格式:
public @interface 注解名 {定義體}
注解參數的可支持數據類型:
1.所有基本數據類型(int,float,boolean,byte,double,char,long,short)
2.String類型
3.Class類型
4.enum類型
5.Annotation類型
6.以上所有類型的數組
Annotation類型里面的參數該怎么設定:
第一,只能用public或默認(default)這兩個訪問權修飾.例如,String value();這里把方法設為defaul默認類型;
第二,參數成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基本數據類型和 String,Enum,Class,annotations等數據類型,以及這一些類型的數組.例如,String value();這里的參數成員就為String;
第三,如果只有一個參數成員,最好把參數名稱設為"value",后加小括號.例:下面的例子FruitName注解就只有一個參數成員。
簡單的自定義注解和使用注解實例:
package annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 水果名稱注解 * @author peida * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitName { String value() default ""; }
package annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 水果顏色注解 * @author peida * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitColor { /** * 顏色枚舉 * @author peida * */ public enum Color{ BULE,RED,GREEN}; /** * 顏色屬性 * @return */ Color fruitColor() default Color.GREEN; }
package annotation; import annotation.FruitColor.Color; public class Apple { @FruitName("Apple") private String appleName; @FruitColor(fruitColor=Color.RED) private String appleColor; public void setAppleColor(String appleColor) { this.appleColor = appleColor; } public String getAppleColor() { return appleColor; } public void setAppleName(String appleName) { this.appleName = appleName; } public String getAppleName() { return appleName; } public void displayName(){ System.out.println("水果的名字是:蘋果"); } }
注解元素的默認值:
注解元素必須有確定的值,要么在定義注解的默認值中指定,要么在使用注解時指定,非基本類型的注解元素的值不可為null。因此, 使用空字符串或0作為默認值是一種常用的做法。這個約束使得處理器很難表現一個元素的存在或缺失的狀態,因為每個注解的聲明中,所有元素都存在,並且都具有相應的值,為了繞開這個約束,我們只能定義一些特殊的值,例如空字符串或者負數,一次表示某個元素不存在,在定義注解時,這已經成為一個習慣用法。
三、自定義注解實例
以上都是一些注解的基礎知識,這里講一下自定義注解的使用。一般,注解都是搭配反射的解析器共同工作的,然后利用反射機制查看類的注解內容。如下:
1 package testAnnotation; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 7 @Documented 8 @Retention(RetentionPolicy.RUNTIME) 9 public @interface Person{ 10 String name(); 11 int age(); 12 }
package testAnnotation; 2 3 @Person(name="xingoo",age=25) 4 public class test3 { 5 public static void print(Class c){ 6 System.out.println(c.getName()); 7 8 //java.lang.Class的getAnnotation方法,如果有注解,則返回注解。否則返回null 9 Person person = (Person)c.getAnnotation(Person.class); 10 11 if(person != null){ 12 System.out.println("name:"+person.name()+" age:"+person.age()); 13 }else{ 14 System.out.println("person unknown!"); 15 } 16 } 17 public static void main(String[] args){ 18 test3.print(test3.class); 19 } 20 }
運行結果:
testAnnotation.test3 name:xingoo age:25
接下來再講一個工作中的例子就可以收篇啦!
LoginVerify注解是用於對標注的方法在進行請求訪問時進行登錄判斷。
- package com.newsee.annotation;
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Inherited;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- /**
- * 是否已登錄判斷
- *
- */
- @Documented
- @Target(ElementType.METHOD)
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- public @interface LoginVerify {
- }
ScanningLoginVerifyAnnotation里的scanning()方法被@PostConstruct修飾,說明它在服務器加載Servlet的時候運行,並且只會被服務器執行一次。
這里再科普一下:
@PostConstruct和@PreDestroy。這兩個注解被用來修飾一個非靜態的void()方法 。寫法有如下兩種方式:
@PostConstruct
Public void someMethod() {}
或者
public @PostConstruct void someMethod(){}
被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct會在構造函數之后,init()方法之前執行。PreDestroy()方法在destroy()方法執行之后執行
scanning方法是在servlet加載完畢后獲取所有被加載類,遍歷其中的方法,如果有被LoginVerify注解修飾,則該方法名放到一個static的map中存儲起來。
- package com.newsee.annotation;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import javax.annotation.PostConstruct;
- import org.springframework.core.io.Resource;
- import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
- import org.springframework.core.io.support.ResourcePatternResolver;
- import org.springframework.stereotype.Component;
- import org.springframework.util.ClassUtils;
- import com.newsee.constant.LoginVerifyMapping;
- @Component
- public class ScanningLoginVerifyAnnotation {
- private static final String PACKAGE_NAME = "com.newsee.face";
- private static final String RESOURCE_PATTERN = "/**/*.class";
- @PostConstruct
- public void scanning() throws IOException, SecurityException,
- ClassNotFoundException {
- String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
- + ClassUtils.convertClassNameToResourcePath(PACKAGE_NAME)
- + RESOURCE_PATTERN;
- ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
- Resource[] resources = resourcePatternResolver.getResources(pattern);
- for (Resource resource : resources) {
- if (resource.isReadable()) {
- String className = getClassName(resource.getURL().toString());
- Class cls = ScanningRequestCodeAnnotation.class.getClassLoader().loadClass((className));
- for (Method method : cls.getMethods()) {
- LoginVerify requestCode = method.getAnnotation(LoginVerify.class);
- if (requestCode != null) {
- </span>LoginVerifyMapping.add(className + "."+ method.getName());
- }
- }
- }
- }
- }
- private String getClassName(String resourceUrl) {
- String url = resourceUrl.replace("/", ".");
- url = url.replace("\\", ".");
- url = url.split("com.newsee")[1];
- url = url.replace(".class", "");
- return "com.newsee" + url.trim();
- }
- }
LoginVerifyMapping就是存放被LoginVerify注解修飾的方法名的。
- public class LoginVerifyMapping {
- private static Map<String, Boolean> faceFunctionIsNeedLoginVerify = new HashMap<String, Boolean>();
- public static void add(String functionName) {
- faceFunctionIsNeedLoginVerify.put(functionName, Boolean.TRUE);
- }
- public static Boolean getFaceFunctionIsNeedLoginVerify(String functionName) {
- return faceFunctionIsNeedLoginVerify.get(functionName);
- }
- }
以下方法就是請求過來時判斷請求的方法是不是在LoginVerifyMapping中,如果是,則需要進行登錄校驗。
- private ResponseContent handleRequests(RequestContent requestContent) throws ClassNotFoundException,
- NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
- InvocationTargetException {
- String requestCode = requestContent.getRequest().getHead().getNWCode();
- String className = RequestCodeMapping.getClassName(requestCode);
- String beanName = RequestCodeMapping.getBeanName(requestCode);
- String functionName = RequestCodeMapping.getFunctionName(requestCode);
- Boolean loginVerify = LoginVerifyMapping.getFaceFunctionIsNeedLoginVerify(className + "." + functionName);
- if (loginVerify != null && loginVerify) {//需要進行登錄校驗
- boolean isAuthenticated = SecurityUtils.getSubject().isAuthenticated();
- if (!isAuthenticated) {
- String exId=requestContent.getRequest().getHead().getNWExID();
- SystemMobileTokenKeyServiceInter systemMobileTokenKeyServiceInter = (SystemMobileTokenKeyServiceInter) SpringContextUtil
- .getBean("systemMobileTokenKeyServiceInter");
- SystemMobileTokenKey systemMobileTokenKey=systemMobileTokenKeyServiceInter.getByExId(exId);
- if(systemMobileTokenKey==null)
- throw new BaseException(ResponseCodeEnum.NO_LOGIN);
- Date keyTime = systemMobileTokenKey.getKeyTime();
- if (System.currentTimeMillis() - keyTime.getTime() > 1000 * 60 * 60 * 24 * 3)
- throw new BaseException(ResponseCodeEnum.NO_LOGIN);
- }
- }
- if (className == null || beanName == null || functionName == null)
- throw new BaseException(ResponseCodeEnum.REQUEST_CODE_NOT_EXIST);
- Object object = SpringContextUtil.getBean(beanName);
- Class cls = Class.forName(className);
- Method method = cls.getMethod(functionName, RequestContent.class);
- Object response = method.invoke(object, requestContent);
- return (ResponseContent) response;
- }
- }