深刻JAVA註解(Annotation):自定義註解 (轉)

原文出自:http://blog.csdn.net/yjclsx/article/details/52101922java

1、基礎知識:元註解spring

 

要深刻學習註解,咱們就必須能定義本身的註解,並使用註解,在定義本身的註解以前,咱們就必需要了解Java爲咱們提供的元註解和相關定義註解的語法。數組

元註解:服務器

  元註解的做用就是負責註解其餘註解。Java5.0定義了4個標準的meta-annotation類型,它們被用來提供對其它 annotation類型做說明。Java5.0定義的元註解:
    1.@Target,
    2.@Retention,
    3.@Documented,
    4.@Inherited
  這些類型和它們所支持的類在java.lang.annotation包中能夠找到。下面咱們看一下每一個元註解的做用和相應分參數的使用說明。app

  @Target:函數

   @Target說明了Annotation所修飾的對象範圍:Annotation可被用於 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。工具

  做用:用於描述註解的使用範圍(即:被描述的註解能夠用在什麼地方)學習

  取值(ElementType)有:ui

    1.CONSTRUCTOR:用於描述構造器
    2.FIELD:用於描述域
    3.LOCAL_VARIABLE:用於描述局部變量
    4.METHOD:用於描述方法
    5.PACKAGE:用於描述包
    6.PARAMETER:用於描述參數
    7.TYPE:用於描述類、接口(包括註解類型) 或enum聲明this

  使用實例:  

複製代碼
@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;
}

2、基礎知識:自定義註解

 

使用@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做爲默認值是一種經常使用的作法。這個約束使得處理器很難表現一個元素的存在或缺失的狀態,由於每一個註解的聲明中,全部元素都存在,而且都具備相應的值,爲了繞開這個約束,咱們只能定義一些特殊的值,例如空字符串或者負數,一次表示某個元素不存在,在定義註解時,這已經成爲一個習慣用法。

3、自定義註解實例

     以上都是一些註解的基礎知識,這裏講一下自定義註解的使用。通常,註解都是搭配反射的解析器共同工做的,而後利用反射機制查看類的註解內容。以下:

 

複製代碼
 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註解是用於對標註的方法在進行請求訪問時進行登陸判斷。

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. package com.newsee.annotation;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. /** 
  11.  * 是否已登陸判斷 
  12.  * 
  13.  */  
  14. @Documented  
  15. @Target(ElementType.METHOD)  
  16. @Inherited  
  17. @Retention(RetentionPolicy.RUNTIME)  
  18. public @interface LoginVerify {  
  19.   
  20. }  

 

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中存儲起來。

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. package com.newsee.annotation;  
  2.   
  3. import java.io.IOException;  
  4. import java.lang.reflect.Method;  
  5. import javax.annotation.PostConstruct;  
  6. import org.springframework.core.io.Resource;  
  7. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  
  8. import org.springframework.core.io.support.ResourcePatternResolver;  
  9. import org.springframework.stereotype.Component;  
  10. import org.springframework.util.ClassUtils;  
  11. import com.newsee.constant.LoginVerifyMapping;  
  12.   
  13. @Component  
  14. public class ScanningLoginVerifyAnnotation {  
  15.     private static final String PACKAGE_NAME = "com.newsee.face";  
  16.   
  17.     private static final String RESOURCE_PATTERN = "/**/*.class";  
  18.   
  19.     @PostConstruct  
  20.     public void scanning() throws IOException, SecurityException,  
  21.             ClassNotFoundException {  
  22.         String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX  
  23.                 + ClassUtils.convertClassNameToResourcePath(PACKAGE_NAME)  
  24.                 + RESOURCE_PATTERN;  
  25.         ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();  
  26.         Resource[] resources = resourcePatternResolver.getResources(pattern);  
  27.         for (Resource resource : resources) {  
  28.             if (resource.isReadable()) {  
  29.                 String className = getClassName(resource.getURL().toString());  
  30.                 Class cls = ScanningRequestCodeAnnotation.class.getClassLoader().loadClass((className));  
  31.                 for (Method method : cls.getMethods()) {  
  32.                     LoginVerify requestCode = method.getAnnotation(LoginVerify.class);  
  33.                     if (requestCode != null) {  
  34.                         </span>LoginVerifyMapping.add(className + "."+ method.getName());  
  35.                     }  
  36.                 }  
  37.             }  
  38.         }  
  39.     }  
  40.   
  41.     private String getClassName(String resourceUrl) {  
  42.         String url = resourceUrl.replace("/", ".");  
  43.         url = url.replace("\\", ".");  
  44.         url = url.split("com.newsee")[1];  
  45.         url = url.replace(".class", "");  
  46.         return "com.newsee" + url.trim();  
  47.     }  
  48. }  

LoginVerifyMapping就是存放被LoginVerify註解修飾的方法名的。

[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. public class LoginVerifyMapping {  
  2.     private static Map<String, Boolean> faceFunctionIsNeedLoginVerify = new HashMap<String, Boolean>();  
  3.   
  4.     public static void add(String functionName) {  
  5.         faceFunctionIsNeedLoginVerify.put(functionName, Boolean.TRUE);  
  6.     }  
  7.   
  8.     public static Boolean getFaceFunctionIsNeedLoginVerify(String functionName) {  
  9.         return faceFunctionIsNeedLoginVerify.get(functionName);  
  10.     }  
  11. }  

如下方法就是請求過來時判斷請求的方法是否是在LoginVerifyMapping中,若是是,則須要進行登陸校驗。

[java]  view plain  copy
 
 在CODE上查看代碼片派生到個人代碼片
  1. private ResponseContent handleRequests(RequestContent requestContent) throws ClassNotFoundException,  
  2.             NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,  
  3.             InvocationTargetException {  
  4.         String requestCode = requestContent.getRequest().getHead().getNWCode();  
  5.         String className = RequestCodeMapping.getClassName(requestCode);  
  6.         String beanName = RequestCodeMapping.getBeanName(requestCode);  
  7.         String functionName = RequestCodeMapping.getFunctionName(requestCode);  
  8.         Boolean loginVerify = LoginVerifyMapping.getFaceFunctionIsNeedLoginVerify(className + "." + functionName);  
  9.         if (loginVerify != null && loginVerify) {//須要進行登陸校驗  
  10.             boolean isAuthenticated = SecurityUtils.getSubject().isAuthenticated();  
  11.             if (!isAuthenticated) {  
  12.                 String exId=requestContent.getRequest().getHead().getNWExID();  
  13.                 SystemMobileTokenKeyServiceInter systemMobileTokenKeyServiceInter = (SystemMobileTokenKeyServiceInter) SpringContextUtil  
  14.                     .getBean("systemMobileTokenKeyServiceInter");  
  15.                 SystemMobileTokenKey systemMobileTokenKey=systemMobileTokenKeyServiceInter.getByExId(exId);  
  16.                 if(systemMobileTokenKey==null)  
  17.                     throw new BaseException(ResponseCodeEnum.NO_LOGIN);  
  18.                 Date keyTime = systemMobileTokenKey.getKeyTime();  
  19.                 if (System.currentTimeMillis() - keyTime.getTime() > 1000 * 60 * 60 * 24 * 3)  
  20.                     throw new BaseException(ResponseCodeEnum.NO_LOGIN);  
  21.             }  
  22.         }  
  23.         if (className == null || beanName == null || functionName == null)  
  24.             throw new BaseException(ResponseCodeEnum.REQUEST_CODE_NOT_EXIST);  
  25.         Object object = SpringContextUtil.getBean(beanName);  
  26.         Class cls = Class.forName(className);  
  27.         Method method = cls.getMethod(functionName, RequestContent.class);  
  28.         Object response = method.invoke(object, requestContent);  
  29.         return (ResponseContent) response;  
  30.     }  
  31. }  
相關文章
相關標籤/搜索