Spring 条件装配 @Conditional

2022-12-24  本文已影响0人  Tinyspot

1. @Conditional

2. @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

4. @ConditionalOnClass

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

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

上一篇 下一篇

猜你喜欢

热点阅读