前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >@ConditionalOnClass注解

@ConditionalOnClass注解

作者头像
黑洞代码
发布2021-06-23 00:32:11
1.4K0
发布2021-06-23 00:32:11
举报

Springboot中为Kafka提供了一个自动配置类

代码语言:javascript
复制
KafkaAutoConfiguration

在KafkaAutoConfiguration类上有一个注解:

代码语言:javascript
复制
@ConditionalOnClass(KafkaTemplate.class)

这个注解通俗的说就是Spring工程中引用了Kafka的包才会构建这个bean。

官方解释:

代码语言:javascript
复制

/**
 * {@link Conditional} that only matches when the specified classes are on the classpath.
 *
 * @author Phillip Webb
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {

   /**
    * The classes that must be present. Since this annotation is parsed by loading class
    * bytecode, it is safe to specify classes here that may ultimately not be on the
    * classpath, only if this annotation is directly on the affected component and
    * <b>not</b> if this annotation is used as a composed, meta-annotation. In order to
    * use this annotation as a meta-annotation, only use the {@link #name} attribute.
    * @return the classes that must be present
    */
   Class<?>[] value() default {};

   /**
    * The classes names that must be present.
    * @return the class names that must be present.
    */
   String[] name() default {};

}

@ConditionalOnClass(KafkaTemplate.class)就是说只有在classpath下能找到KafkaTemplate类才会构建这个bean。

其他类似注解:

@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean) @ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean) @ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean) @ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean) @ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean) @ConditionalOnNotWebApplication(不是web应用)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 落叶飞翔的蜗牛 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档