Spring支持按照条件来注入某些特定的bean,这也是Spring Boot实现自动化配置的底层方法
基本方法
- 使用样例
//满足条件WindowsCondition才会注入UserManager到Spring上下文
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
XXX
}
- 所有的条件都必须实现接口
Condition
@FunctionalInterface
public interface Condition {
/**
* Determine if the condition matches.
* @param context the condition context
* @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
* or {@link org.springframework.core.type.MethodMetadata method} being checked
* @return {@code true} if the condition matches and the component can be registered,
* or {@code false} to veto the annotated component's registration
*/
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
使用自定义条件
- 自定义条件
WindowsCondition
/**
* 判断是否是Windows系统.
*/
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String property = environment.getProperty("os.name");
return property.contains("Windows");
}
}
- 使用
@Slf4j
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
@PostConstruct
private void init() {
log.info("UserManager init");
}
}
- 启动
启动命令添加--os.name=Windows
后,日志输出"UserManager init"
网友评论