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

如何在Spring Boot应用中自动读取spring.config.additional-location的值

在Spring Boot中读取spring.config.additional-location的几种方法

首先明确:你用--spring.config.additional-location传入的是Spring命令行配置参数,并非JVM系统属性(系统属性是-D开头的),所以System.getProperty()肯定拿不到,得用Spring自身的配置读取机制。

下面是几种不用System.getProperty()的实现方式:

方法一:用@Value注解直接注入

这是最简单的方式,直接把配置值注入到类的字段里:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConfigLocationReader {

    // 注入配置值,冒号后是空默认值,避免配置未传入时报错
    @Value("${spring.config.additional-location:}")
    private String additionalConfigLocation;

    public void printConfigLocation() {
        System.out.println("spring.config.additional-location: " + additionalConfigLocation);
    }
}

只要这个类被Spring容器管理(加了@Component或其他衍生注解),启动后就能直接拿到启动命令里传入的路径。

方法二:通过Environment对象获取

如果需要更灵活的读取逻辑(比如动态判断配置是否存在),可以注入Spring的Environment接口:

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class ConfigLocationReader {

    private final Environment environment;

    // 构造方法注入Environment
    public ConfigLocationReader(Environment environment) {
        this.environment = environment;
    }

    public void getConfigLocation() {
        String location = environment.getProperty("spring.config.additional-location");
        if (location != null) {
            System.out.println("额外配置路径:" + location);
        } else {
            System.out.println("未设置额外配置路径");
        }
    }
}

Environment能获取所有Spring加载的配置属性,包括命令行参数、配置文件、系统属性等,优先级遵循Spring的配置规则。

方法三:在启动回调中读取

如果需要在应用启动完成后立刻读取这个值,可以实现ApplicationRunner或CommandLineRunner接口:

import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class StartupConfigReader implements ApplicationRunner {

    private final Environment environment;

    public StartupConfigReader(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void run(org.springframework.boot.ApplicationArguments args) throws Exception {
        String location = environment.getProperty("spring.config.additional-location");
        System.out.println("启动时传入的额外配置路径:" + location);
    }
}

应用启动后,这个run方法会自动执行,直接拿到配置值。

注意事项

  • 如果启动时传入了多个spring.config.additional-location(用逗号分隔),读取到的是逗号拼接的字符串,比如file:/path1/,file:/path2/
  • 命令行参数的优先级高于配置文件,所以你读取到的一定是启动命令里传入的那个值,不会被配置文件覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:05:16