最近研究多數據源問題,使用的是druid鏈接池,多數據源經過註解自動配置,使用這三個註解 @Retention @Documented @Inherited 自定義一個註解配置數據源html
Retention註解:- Retention(保留)註解說明,這種類型的註解會被保留到那個階段java
有三個值:工具
1.RetentionPolicy.SOURCE —— 這種類型的Annotations只在源代碼級別保留,編譯時就會被忽略 2.RetentionPolicy.CLASS —— 這種類型的Annotations編譯時被保留,在class文件中存在,但JVM將會忽略測試
3.RetentionPolicy.RUNTIME —— 這種類型的Annotations將被JVM保留,因此他們能在運行時被JVM或其餘使用反射機制的代碼所讀取和使用. 示例1演示了 RetentionPolicy.RUNTIME 的聲明: Java註解的示例1:ui
@Retention(RetentionPolicy.RUNTIME) public @interface TestRetention { .net
String doTestRetention();htm
} 對象
在這個示例中, @Retention(RetentionPolicy.RUNTIME)註解代表 TestRetention註解將會由虛擬機保留,以便它能夠在運行時經過反射讀取.blog
Documented 註解:繼承
Documented 註解代表這個註解應該被 javadoc工具記錄. 默認狀況下,javadoc是不包括註解的. 但若是聲明註解時指定了 @Documented,則它會被 javadoc 之類的工具處理, 因此註解類型信息也會被包括在生成的文檔中. 示例2進一步演示了使用 @Documented:
Java註解的示例2:
@Documented public @interface TestDocumented {
String doTestDocument();
}
接下來,像下面這樣修改TestAnnotations類:
public class TestAnnotations {
public static void main(String arg[]) {
new TestAnnotations().doSomeTestRetention();
new TestAnnotations().doSomeTestDocumented();
}
@TestRetention (doTestRetention="保留註解信息測試")
public void doSomeTestRetention() { System.ou
t.printf("測試註解類型 'Retention'"); }
@Test_Documented(doTestDocument="Hello document")
public void doSomeTestDocumented()
{ System.out.printf("測試註解類型 'Documented'"); } }
如今,若是使用 javadoc命令生成 TestAnnotations.html文件,你將看到相似於圖1的結果.
Inherited 註解 這是一個稍微複雜的註解類型. 它指明被註解的類會自動繼承. 更具體地說,若是定義註解時使用了 @Inherited 標記,而後用定義的註解來標註另外一個父類, 父類又有一個子類(subclass),則父類的全部屬性將被繼承到它的子類中. 在示例7中,你會看到使用 @Inherited 標籤的好處.
Java註解的示例3
首先,定義你的註解:
@Inherited
public @interface MyParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}
接下來,使用註解標註了一個類:
@MyParentObject
public Class MyChildObject { }
正如你看到的,你不須要在實現類中定義接口方法. 由於使用 @Inherited標記,這些都自動繼承了. 若是你使用一種古老的方式定義實現類,會是什麼樣子呢? 看看下面這張 古老的實現方式吧:
public class MyChildObject implements MyParentObject {
public boolean isInherited() { return false; }
public String doSomething() { return ""; }
public boolean equals(Object obj) { return false; }
public int hashCode() { return 0; }
public String toString() { return ""; }
public Class annotationType() { return null; }
}
看到的區別嗎? 能夠看到,你必須實現父接口的全部方法.
除了isInherited()和從myParentObject doSomething()方法外,
你還須要實現 java.lang.Object的
equals(),
toString()
和hasCode()方法.
還有 java.lang.annotation.Annotation 類的
annotationType()方法. 無論你是否是想要實現這些方法,你必須在繼承的對象中包含這些.