Spring注解@AutoConfigureAfter @AutoConfigureBefore @conditional

654 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情

一、Spring注解@AutoConfigureAfter @AutoConfigureBefore

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Documented
public @interface AutoConfigureAfter/AutoConfigureBefore {

   /**
    * The auto-configure classes that should have already been applied.
    * @return the classes
    */
   Class<?>[] value() default {};

   /**
    * The names of the auto-configure classes that should have already been applied.
    * @return the class names
    * @since 1.2.2
    */
   String[] name() default {};

}

@AutoConfigureBefore 和 @AutoConfigureAfter 是 spring-boot-autoconfigure 包下的注解

@AutoConfigureAfter 在加载配置的类之后再加载当前类 它的value 是一个数组 一般配合着**@import** 注解使用 ,在使用import时必须要让这个类先被spring ioc 加载好

@AutoConfigureBefore(AAAA.class) 或 AutoConfigureBefore({AAAA.class, BBBB.class})
@AutoConfigureBefore(AAAA.class)
public class CCCC {
}

说明 CCCC 将会在 AAAA 之前加载

@AutoConfigureAfter(AAAA.class) 或 AutoConfigureAfter({AAAA.class, BBBB.class})
@AutoConfigureAfter(AAAA.class)
public class CCCC {
}

说明 CCCC 将会在 AAAA 之后加载

二、Spring注解@conditional

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

   /**
    * All {@link Condition} classes that must {@linkplain Condition#matches match}
    * in order for the component to be registered.
    */
   Class<? extends Condition>[] value();

}

@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。

@ConditionalOnClass(A.class):只有当类A存在时,才能实例化B类;存在某个类时,才会实例化一个Bean。

@ConditionalOnMissingClass(A.class)(不存在A类时,才会实例化一个Bean)

@ConditionalOnBean("connectionFactory")当Bean存在connectionFactory才实例化bean

@ConditionalOnProperty(name = "mqtt.aliyun.enable", havingValue = "true")当属性存在值才实例化。

@ConditionalOnMissingBean(name = “connectionFactory”) 不存在connectionFactory个bean的时候实例化。

@ConditionalOnMissingBean(annotation = EnableSyjRateLimit.class)根据注解等等骚操作都可以。

@ConditionalOnProperty(prefix = “syj”, name = “algorithm”, havingValue = “token”)

这个就稍微复杂了一点,它的意思呢

就是当存在配置文件中以syj为前缀的属性,属性名称为algorithm,然后它的值为token时才会实例化一个类。

而且这个还有一个比较好的属性 @ConditionalOnProperty(prefix = “syj”, name = “algorithm”, havingValue = “counter”, matchIfMissing = true)

matchIfMissing的意思呢就是说如果所有的都不满足的话就默认实现,不管这个属性syj.algorithm是不是等于counter。

@ConditionalOnExpression("!'${spring.redis.host:}'.isEmpty()")当参数redis.host不为空的时候注入注解bean。

@ConditionalOnJava(如果是Java应用)

@ConditionalOnWebApplication(如果是Web应用)

@Import注解能定义单个类的bean

@Import({Role.class, User.class})