Spring@ConditionalOnBean注解
@ConditionalOnBean作⽤:放在 @Bean 注解上,如果@ConditionalOnBean注解参数中指定的bean存在,就实例化当前作⽤的Bean # 当给定的在bean存在时,则实例化当前Bean
@ConditionalOnBean
# 当给定的在bean不存在时,则实例化当前Bean
怎样交朋友stack@ConditionalOnMissingBean
# 当给定的类名在类路径上存在,则实例化当前Bean
moulds@ConditionalOnClass
# 当给定的类名在类路径上不存在,则实例化当前Bean
@ConditionalOnMissingClass
1、City类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
here you are是什么意思
public class City {
private String cityName;
private Integer citySize;wgl
}
新视野大学英语2课文翻译幼儿英语歌曲2、Ur类
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Ur {
private String name;
private Integer age;
private City city;
}
3、配置类
@Configuration
public class ConditionalConfig {
// @Bean
novelty
// public City city(){
/
stamina/ City city = new City();
// city.tCityName("beijing");
// return city;
// }
//当city的bean存在时,才会将ur注⼊到spring中,否则报null
@ConditionalOnBean(name ="city")
@Bean
public Ur ur(){
City city =new City();
city.tCityName("shanghai");
city.tCitySize(20);
return new Ur("zhangsan",2,city);
}
}
4、测试类
@RunWith(SpringRunner.class)表示热烈的祝贺
@SpringBootTest
public class ConditionalOnDemo {
@Autowired(required =fal)
Ur ur;
@Test
public void run(){
System.out.println("ur is:"+ur);
}
}
当Spring没有注⼊City的bean时,就会报空
ur is:null
当Spring注⼊City的bean时,就会正常执⾏,将ur的bean注⼊到spring容器中ur is:Ur(name=zhangsan, age=2, city=City(cityName=beijing, citySize=20))