美文网首页
Spring 条件装配 @Conditional

Spring 条件装配 @Conditional

作者: Tinyspot | 来源:发表于2022-12-24 18:06 被阅读0次

1. @Conditional

  • 条件装配:满足Conditional指定的条件,则进行组件注入

2. @ConditionalOnBean

  • @Bean 将组件注入容器
  • @ConditionalOnBean 当容器中存在这个类型组件,才进行组件注入
  • @ConditionalOnBean 加在方法上时,只限定单个组件注入成功与否
  • @ConditionalOnBean 加在配置类上时,若配置类注入不成功,里面的组件都不会注入成功

2.1 正常注入依赖

@Configuration
public class UserConfig {

    @Bean
    public User user() {
        User user = new User();
        user.setOrder(order()); // 依赖 order 组件
        return user;
    }

    @Bean
    public Order order() {
        return new Order();
    }
}

测试:

public static void main(String[] args) {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(ConbootStarterApplication.class, args);
    System.out.println("contains userConfig: " + applicationContext.containsBean("userConfig"));
    System.out.println("contains user: " + applicationContext.containsBean("user"));
    System.out.println("contains order: " + applicationContext.containsBean("order"));
}

若不注入 Order 组件

// @Bean
public Order order() {
    return new Order();
}

打印结果:
contains UserConfig: true
contains user: true
contains order: false

2.2 @ConditionalOnBean 加到方法上

用 @ConditionalOnBean 限制,当 Order 未注入时,User 也不注入

@Configuration
public class UserConfig {

    // @Bean
    public Order order() {
        return new Order();
    }

    @Bean
    @ConditionalOnBean(Order.class)
    // @ConditionalOnBean(name = "order")
    public User user() {
        User user = new User();
        user.setOrder(order());
        return user;
    }
}

打印结果
contains UserConfig: true
contains user: false
contains order: false

2.3 @ConditionalOnBean 加到配置类上

@Configuration
@ConditionalOnBean(Order.class)
public class UserConfig {

    // @Bean
    public Order order() {
        return new Order();
    }

    @Bean
    public User user() {
        User user = new User();
        user.setOrder(order());
        return user;
    }
}

打印结果
contains UserConfig: false
contains user: false
contains order: false

2.4 @ConditionalOnBean失效

  • 条件注解中的条件组件必须要先完成注册
@Configuration
public class UserConfig {

    @Bean // 放到前面
    public Order order() {
        return new Order();
    }

    @Bean
    @ConditionalOnBean(Order.class)
    public User user() {
        User user = new User();
        user.setOrder(order());
        return user;
    }
}

3. @ConditionalOnMissingBean

  • 与@ConditionalOnBean刚好相反

4. @ConditionalOnClass

@Bean
@ConditionalOnClass(Order.class)
public User user() {
    User user = new User();
    user.setOrder(order());
    return user;
}

其他:
name 属性指定的是全类名

相关文章

网友评论

      本文标题:Spring 条件装配 @Conditional

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