bena的加载控制指:根据特定情况对bean进行选择性加载以达到适用于项目的目标
编程式
- 根据任意条件确认是否加载bean
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata){
try {
Class<?> clazz = Class.forName("com.java.bean.Mouse");
if (clazz != null){
return new String[]{"com.java.bean.Cat"};
}
} catch (ClassNotFoundException e) {
return new String[0];
}
return null;
}
}
注解式
- 使用@Conditional注解的派生注解设置各种组合条件控制bean的加载
- 匹配指定类/指定bean/指定环境
public class SpringConfig {
@Bean
// @ConditionalOnClass(name = "com.java.bean.Mouse")
// @ConditionalOnMissingClass("com.java.bean.Wolf")
// @ConditionalOnBean(name="com.java.bean.Mouse")
// @ConditionalOnBean(name="jerry")
// @ConditionalOnMissingClass("com.java.bean.Dog")
// @ConditionalOnWebApplication
// @ConditionalOnNotWebApplication
public Cat tom(){
return new Cat();
}
}