You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中实现Condition接口的内部类无法读取application.yml属性

解决Spring Boot中Condition无法获取@Value注入属性的问题

核心原因

  • Condition执行时机过早:Spring在判断是否创建Bean时,会优先调用Condition的matches方法,此时目标Bean(比如Mydemo)还未完成实例化和属性注入,所以@Value标记的属性自然是null。
  • 内部类的额外影响:成员内部类默认持有外部类实例引用,但外部类还未初始化,引用对象的属性也不会有值。即使去掉内部类,只要Condition的执行时机不变,依然拿不到注入的属性。

可行解决方案

方案1:通过ConditionContext直接读取配置

利用ConditionContext提供的Environment对象,直接从环境中读取配置属性,无需依赖Bean注入:

@Component
public class Mydemo {

    public static class innerDemo implements Condition { // 改为静态内部类,避免依赖外部类实例
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metaData) {
            String propertyValue = context.getEnvironment().getProperty("key.something");
            System.out.println(propertyValue); // 输出Hello
            return true;
        }
    }
}

注意:成员内部类要改为静态内部类,否则会因外部类未实例化导致无法正常使用。

方案2:使用@ConfigurationProperties绑定配置

如果需要读取多个相关配置,推荐用@ConfigurationProperties统一绑定,再通过Environment获取:

  1. 定义配置绑定类:
@ConfigurationProperties(prefix = "key")
public class KeyProperties {
    private String something;

    // getter、setter
    public String getSomething() {
        return something;
    }

    public void setSomething(String something) {
        this.something = something;
    }
}
  1. 在启动类或配置类中启用配置绑定:
@SpringBootApplication
@EnableConfigurationProperties(KeyProperties.class)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 修改Condition读取绑定后的属性:
public class MyDemoCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        KeyProperties properties = context.getEnvironment().getProperty(KeyProperties.class);
        System.out.println(properties.getSomething()); // 输出Hello
        return true;
    }
}

方案3:避免用Condition做Bean初始化后的判断(不推荐)

Condition的设计初衷是在Bean创建前做条件判断,如果硬要在Bean初始化后获取属性,违背了它的设计逻辑。这种场景下,建议用@PostConstruct或ApplicationListener来实现相关逻辑。

内容的提问来源于stack exchange,提问作者geeta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 16:00:10