美文网首页
Spring的条件注入的原理及使用

Spring的条件注入的原理及使用

作者: 十毛tenmao | 来源:发表于2021-06-08 09:37 被阅读0次

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"

参考

相关文章

网友评论

      本文标题:Spring的条件注入的原理及使用

      本文链接:https://www.haomeiwen.com/subject/yexdeltx.html