前言
最近開始接觸spring-boot,它能減少項目的配置文件數量,讓項目結構變得極簡併且提高開發效率。之所以能夠極簡,最大的原因就是spring-boot提供了一大堆(讓我)”不知所謂”的註解,是最讓我懵比的一點。而且我發現自己註解的基本知識幾乎忘光了。所以有必要重新pick up一下基礎知識。(尷尬-_-|||)
註解的作用
To be filled…
例子
@MyAnno.java
@Retention(RetentionPolicy.RUNTIME)//運行時起作用
@Target(ElementType.TYPE)//改註解作用於類或接口
public @interface MyAnno {
public String value() default "";
}
@AnnoMethod.java
@Retention(RetentionPolicy.RUNTIME)//works when runtime
@Target(ElementType.METHOD)//works on method...
public @interface AnnoMethod {
public String value() default "";
}
A.java
@MyAnno(value="new value is xxx")
public class A {
}
TestMyAnno.java
public class TestMyAnno {
public static void main(String[] args) {
Class<A> clazz = A.class;
Annotation[] annotations = clazz.getAnnotations();
System.out.println(annotations.length);
for (Annotation annotation : annotations) {
if(annotation instanceof MyAnno) {
System.out.println(annotation.getClass().getName());
MyAnno anno = (MyAnno)annotation;
System.out.println(anno.value());
}
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(AnnoMethod.class)) {
AnnoMethod am = method.getAnnotation(AnnoMethod.class);
System.out.println(am.value());
}
}
}
}