1. 基于 @Conditional 的注解
- @ConditionalOnBean
- @ConditionalOnMissingBean
- @ConditionalOnClass
- @ConditionalOnMissingClass
1.1 Spring 的依赖注入
@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. 条件装配 @ConditionalOnBean
- 有指定的 Bean 时,才会加载当前bean
- @ConditionalOnBean 装配顺序
2.1 @ConditionalOnBean 加到方法上
@Configuration
public class UserConfig {
/**
* 条件注解中的条件组件必须要先完成注册
* Order 注入需要放到前面
*/
@Bean
public Order order() {
return new Order();
}
// 当 Order 未注入时,User 也不注入
@Bean
@ConditionalOnBean(Order.class)
// @ConditionalOnBean(name = "order")
public User user() {
User user = new User();
user.setOrder(order());
return user;
}
}
2.2 @ConditionalOnBean 加到配置类上
- @ConditionalOnBean 加在配置类上时,若配置类注入不成功,里面的组件都不会注入成功
方式一:属性方式
@Configuration
@ConditionalOnBean(Order.class)
public class BeanConditionOnConfig {
@Resource
private Order order;
@Bean
public User user() {
User user = new User();
user.setOrder(order);
return user;
}
}
方式二:方法参数注入
@Configuration
@ConditionalOnBean(Order.class)
public class BeanConditionOnConfig {
@Bean
public User user(Order order) {
User user = new User();
user.setOrder(order);
return user;
}
}
2.3 @ConditionalOnMissingBean
@Configuration
@ConditionalOnMissingBean(Order.class)
public class BeanConditionOnConfig {
@Bean
public User user() {
return new User();
}
}
4. @ConditionalOnClass
@Configuration
public class BeanConditionOnConfig {
@Bean
@ConditionalOnClass(value = {Order.class, OtherClass.class})
public User user(Order order, OtherClass otherClass) {
User user = new User();
user.setOrder(order);
return user;
}
}
@Data
@Component
public class Order {
private Long orderId;
private String orderCode;
}
@Component
public class OtherClass {
}
4.1 其他
public @interface ConditionalOnClass {
Class>[] value() default {};
// 全类名
String[] name() default {};
}
【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】
© 版权声明
部分内容为互联网分享,若有侵权请联系站长删除。
THE END
暂无评论内容