@ConditionalOnBean详解
为什么学习@ConditionalOnBean
在学习 Springboot 自动装配的时候遇到 Bean 装配和 Bean 配置需要条件判断的场景时,查阅了相关内容了解到 @Conditional 和 @ConditionalOnBean 注解,深入学习之后受益匪浅。
@ConditionalOnBean测试
如果要完成 Student 类往 Spring 容器中注入时,判断 School 存在时注入,不存在则不注入。
Student 类:
@Data
@AllArgsConstructor
public class Student {
private String name;
}
School 类:
@Data
@AllArgsConstructor
public class School {
private String name;
}
配置类:
@Configuration
public class BeanConfiguration {
@ConditionalOnBean(School.class)
@Bean("zhangsan")
public Student student() {
return new Student("张三");
}
}
当注入 School 时测试启动类:
@Configuration
public class BeanConfiguration {
@Bean
public School school() {
return new School("清华大学");
}
@ConditionalOnBean(School.class)
@Bean("zhangsan")
public Student student() {
return new Student("张三");
}
}
结果:
当不注入 School 时测试启动类:
@Configuration
public class BeanConfiguration {
// @Bean
// public School school() {
// return new School("清华大学");
// }
@ConditionalOnBean(School.class)
@Bean("zhangsan")
public Student student() {
return new Student("张三");
}
}
结果: