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 属性指定的是全类名
网友评论