Bean的加载控制
文章目录
- Bean的加载控制
- 编程式
- 注解式@ConditionalOn***
编程式
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
try {
Class<?> clazz = Class.forName("com.itheima.bean.Mouse");
if(clazz != null){
return new String[]{"com.itheima.bean.Cat"};
}
} catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
return new String[0];
}
return null;
}
}
注解式@ConditionalOn***
使用@Conditional注解的派生注解设置各种组合条件控制bean的加载
@Component("tom")
@ConditionalOnBean(name = "com.itheima.bean.Mouse")
//@ConditionalOnNotWebApplication
@ConditionalOnWebApplication
public class Cat {
}
组合条件
应用一下,根据是否使用 jdbc来决定加载不加载对应的bean
//@Import(MyImportSelector.class)
@ComponentScan("com.itheima.bean")
public class SpringConfig {
/*
@Bean
// @ConditionalOnClass(Mouse.class) //ConditionalOnClas是Conditional的注解下面的,可以Ctrl + h查看到
// @ConditionalOnClass(name = "com.itheima.bean.Mouse") //ConditionalOnClas是Conditional的注解下面的,可以Ctrl + h查看到
// @ConditionalOnMissingClass("com.itheima.bean.Wolf") // 点进去看看,人家让写String
// @ConditionalOnBean(name = "com.itheima.bean.Mouse")
@ConditionalOnNotWebApplication
public Cat tom(){
return new Cat();
}
*/
@Bean
@ConditionalOnClass(name = "com.mysql.jdbc.Driver")
public DruidDataSource dataSource(){
return new DruidDataSource();
}
}