前言
最近开始接触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());
}
}
}
}