@Conditional
- 按照条件创建对象放入容器
1. 测试代码
@ComponentScan("com.alex.person")
@Configuration
public class ConditionalConfig {
@Conditional({MacOSCondition.class})//如果这个类条件通过就加载
@Bean
public Person person() {
return new Person(1, "alex");
}
}
public class MacOSCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
// bean定义的注册类
context.getRegistry();
metadata.getAnnotations();
String properties = env.getProperty("os.name");
if (properties.contains("Mac OS X")) { // 如果是mac系统就加载
System.out.println("允许注入 系统: " + properties);
return true;
}
return false;
}
}
结果
允许注入 系统: Mac OS X
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
conditionalConfig
person
personServiceImpl
- 小结 @Conditional(xxx.class) 根据这个实现Condition接口的类来判断是否将这个bean放入容器,如果不满足会报错! 这是最简单的使用.