@ConditionalOnClass注解分析

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

KafkaAutoConfiguration

在类上有一个注解

@ConditionalOnClass(KafkaTemplate.class)

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

官方解释:

/**
 * {@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
    * not 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 {};

}

就是说只有在classpath下能找到kafkaTemplate类才会构建这个bean。

其他类似注解:

@Conditional(TestCondition.class)

这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置,也可以标注在方法上面,只是对该方法启用配置。

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

你可能感兴趣的:(SpringBoot,SpringBoot注解)