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

如何在Spring Boot中不依赖注入通过Environment API获取属性值

解决方案:无注入通过Environment获取属性值

因为你无法使用字段/构造器注入,且私有方法里@Value注解无法生效,这里提供一种通过静态持有Spring上下文获取Environment实例的方案:

步骤1:创建ApplicationContext持有类

实现ApplicationContextAware接口,让Spring自动注入上下文并静态持有:

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

步骤2:在目标方法中获取Environment并取值

直接通过持有类获取上下文,再拿到Environment实例调用getProperty:

public int getCustomProperty(String key) {
    Environment env = ApplicationContextHolder.getApplicationContext().getEnvironment();
    // 可添加默认值避免key不存在时返回null抛出异常
    return env.getProperty(key, Integer.class, 0);
}

注意事项

  • 确保ApplicationContextHolder所在包被Spring的组件扫描覆盖(@ComponentScan)
  • 仅在Spring上下文初始化完成后调用该方法,避免空指针异常
  • 静态持有上下文会增加代码耦合度,非必要场景优先使用Spring的依赖注入机制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:17:07