美文网首页
annotation

annotation

作者: 一笑yo | 来源:发表于2017-02-07 17:39 被阅读0次

1.5之后java带来了注解.注解一般通过配置@Target,@Retention,@Documented就可以创建自己的注解了.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface A{

}

如何使用注解? 我们知道可以通过java的反射机制来获取到注解以及注解内容.但是今天看源码时候突然发现一个很有意思的使用方法.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(B.class)
public @interface A{

}

@Configuration
public class B{
    class C{}

    @Bean
    public C enableC() {
        return new C();
    }
}

@Configuration
@ConditionalOnBean(B.C.class)
@Import({E.class,F.class})
public class D{

}

在spring中,

  • 创建一个注解,该注解注入了一个Bean C,
  • 如果用户引用了该注解,则配置文件D中就会判断是否已经存在C,
  • 如果存在则加载E,F配置.

这样就相当于用户引入一个annotation就完成了EF的配置信息加载.(感觉我们只需要引入一个annotation就增加了一些特性)

相关文章

网友评论

      本文标题:annotation

      本文链接:https://www.haomeiwen.com/subject/gndmittx.html