前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring的条件注入的原理及使用

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

作者头像
十毛
发布2021-06-11 18:06:28
4920
发布2021-06-11 18:06:28
举报
文章被收录于专栏:用户1337634的专栏

Spring支持按照条件来注入某些特定的bean,这也是Spring Boot实现自动化配置的底层方法

基本方法

  • 使用样例
代码语言:javascript
复制
//满足条件WindowsCondition才会注入UserManager到Spring上下文
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
    XXX
}
  • 所有的条件都必须实现接口Condition
代码语言:javascript
复制
@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
代码语言:javascript
复制
/**
 * 判断是否是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");
    }
}
  • 使用
代码语言:javascript
复制
@Slf4j
@Component
@Conditional(WindowsCondition.class)
public class UserManager {
    @PostConstruct
    private void init() {
        log.info("UserManager init");
    }
}
  • 启动 启动命令添加--os.name=Windows后,日志输出"UserManager init"

参考

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基本方法
  • 使用自定义条件
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档