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

如何在工具类中访问@ConfigurationProperties配置属性值

解决方案:Spring工具类访问@ConfigurationProperties属性

问题场景

现有配置类AppProperties存储应用配置:

@Configuration
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
    private List<String> listValue;
    private boolean booleanValue = true;
    private String stringValue;
}

工具类MyUtil构造方法私有,仅提供静态方法,需在doJob()中访问stringValue:

@Slf4j
public class MyUtil {

    private MyUtil() {
        throw new UnsupportedOperationException();
    }

    public static String doJob() {
        log.debug(stringValue); // 需要访问此处的stringValue
    }
}

以下是不修改工具类结构的可行方案:


方案1:通过ApplicationContextHolder获取配置Bean

先实现一个持有Spring上下文的工具类,让MyUtil通过它获取AppProperties实例:

步骤1:创建ApplicationContextHolder

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

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

    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }
}

步骤2:修改MyUtil的doJob方法

public static String doJob() {
    AppProperties appProperties = ApplicationContextHolder.getBean(AppProperties.class);
    String stringValue = appProperties.getStringValue();
    log.debug(stringValue);
    return stringValue;
}

方案2:在配置类中暴露静态实例

让AppProperties在Spring初始化时把自身实例存入静态字段,MyUtil直接调用静态方法获取:

步骤1:修改AppProperties

@Configuration
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
    private static AppProperties instance;

    private List<String> listValue;
    private boolean booleanValue = true;
    private String stringValue;

    @PostConstruct
    public void init() {
        instance = this;
    }

    public static AppProperties getInstance() {
        return instance;
    }
}

步骤2:修改MyUtil的doJob方法

public static String doJob() {
    String stringValue = AppProperties.getInstance().getStringValue();
    log.debug(stringValue);
    return stringValue;
}

注意事项

  • 方案1需确保ApplicationContextHolder被Spring扫描到(处于@ComponentScan范围内)。
  • 方案2依赖AppProperties的单例特性(Spring默认Bean为单例),避免多实例覆盖静态字段。
  • 两种方案均无需修改MyUtil的私有构造和静态方法结构,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:36:09