@Conditional 按照条件注入bean,也可以放在配置类上统一设置条件
配置类:
@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {
/**
* @Conditional 按照条件注入bean
* 如果系统是windows则注入该bean
*/
@Conditional(WindowsCondition.class)
@Bean
public Person person01(){
System.out.println("person01..被创建放入ioc容器...");
return new Person("windows","22");
}
/**
* @Conditional 按照条件注入bean
* 如果系统是linux则注入该bean
*/
@Conditional(LinuxCondition.class)
@Bean
public Person person02(){
System.out.println("person02..被创建放入ioc容器...");
return new Person("linux","20");
}
}
自定义实现条件:
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String property = context.getEnvironment().getProperty("os.name");
//获取本机操作系统名称
if (property.contains("Windows")){
return true;
}
return false;
}
}
public class LinuxCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
ClassLoader classLoader = context.getClassLoader();
//获取本机操作系统名称
String property = context.getEnvironment().getProperty("os.name");
if (property.contains("Linux")){
return true;
}
return false;
}
}
main方法测试ing:
本机为windows系统,结果只向容器中注入了person01方法的对象