@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
String value() default "";
}
我有一个对象被@Configuration注解,那我怎么知道它还是被Component注解的?@Interface
和接口Annotation
是什么关系?
有一个注解了@Configuration的对象, obj.getClass().getAnnotation(Configuration.class).getClass()==Configuration.class
结果是false, obj.getClass().getAnnotation(Configuration.class) instanceof Configuration
为true, obj.getClass().getAnnotation(Configuration.class) instanceof Component
为false
Annotation
也可以获取自身的注解。@interface
是声明注解的关键字(与class/interface
一样)obj.getClass().getAnnotation(Configuration.class).getClass() == Configuration.class
引用不同结果为false
是正常情况。可以使用这种判断obj.getClass().getAnnotation(Configuration.class).getClass().getName().equals(Configuration.class.getName())
@Component
只是@Configuration
的注解声明,并不表示@Configuration
就是@Component
类型另外上面这种用法叫
Meta-Annotations
在 spring-4.1.x 之后的的版本都支持这个功能,可以自定义Annotation
,声明Meta-Annotations
即可拥有相对的功能。beans-meta-annotations
Spring Annotation Programming Model
注:
Meta-Annotations
并不是Annotation
的原生功能,只是在spring
中实现了这种机制。如果单纯的使用原生的Annotation
则需要自己解析Meta-Annotations
实现相应的功能才行。