@ConditionalOnBean作用:放在 @Bean 注解上,如果@ConditionalOnBean注解参数中指定的bean存在,就实例化当前作用的Bean
# 当给定的在bean存在时,则实例化当前Bean
@ConditionalOnBean
# 当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnMissingBean
# 当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnClass
# 当给定的类名在类路径上不存在,则实例化当前Bean
@ConditionalOnMissingClass
1、City类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class City {
private String cityName;
private Integer citySize;
}
2、User类
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private Integer age;
private City city;
}
3、配置类
@Configuration
public class ConditionalConfig {
// @Bean
// public City city(){
// City city = new City();
// city.setCityName("beijing");
// return city;
// }
//当city的bean存在时,才会将user注入到spring中,否则报null
@ConditionalOnBean(name = "city")
@Bean
public User user(){
City city = new City();
city.setCityName("shanghai");
city.setCitySize(20);
return new User("zhangsan",2,city);
}
}
4、测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConditionalOnDemo {
@Autowired(required = false)
User user;
@Test
public void run(){
System.out.println("user is:"+user);
}
}
当Spring没有注入City的bean时,就会报空
user is:null
当Spring注入City的bean时,就会正常执行,将user的bean注入到spring容器中
user is:User(name=zhangsan, age=2, city=City(cityName=beijing, citySize=20))