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"