【问题标题】:How to load external properties file and override springboot application.properties (without runtime args)?如何加载外部属性文件并覆盖spring boot application.properties(没有运行时参数)?
【发布时间】:2019-11-06 19:36:56
【问题描述】:

我想加载 springboot 应用程序之外的属性文件,并在运行时环境中以编程方式覆盖与 sprignboot 匹配的应用程序属性,而不是通过服务器上下文/运行时参数?

我找到了一种通过为 ApplicationEnvironmentPreparedEvent 创建侦听器来实现这一点的方法。 工作代码示例链接: https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.core.env.ConfigurableEnvironment

但正在寻找更简单的 Spring Boot 托管解决方案

类似这样的东西(虽然下面的代码不起作用):

SpringApplication application = new SpringApplication(MainApplication.class);
application.setBannerMode(Mode.OFF);
Properties props = new Properties();
try{
 props.load(newFileInputStream(
   "C:\\...\\PropFile\\applicationconfig.properties"));
application.setDefaultProperties(props);
application.run(args);
} catch (Exception e) {
//print exception here;
}

【问题讨论】:

  • 你可以看看这个教程 baeldung.com/spring-reloading-properties
  • "C:\\...\\PropFile\\applicationconfig.properties"));。你不觉得这条路不对吗?没有这样的...。
  • @Jonathan,我会尽力让你知道(我在教程中看到的一件事是我们必须将文件路径作为 CL 参数传递。在我的情况下,我没有那个选项)。
  • @ialam,我只是给出了一个路径示例。我知道“...”不正确。

标签: java spring-boot application.properties


【解决方案1】:

您可以使用 spring EnvironmentPostProcessor 实现相同的效果。

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Resource path = new ClassPathResource("com/example/myapp/config.yml");
        PropertySource<?> propertySource = loadYaml(path);
        environment.getPropertySources().addLast(propertySource);
    }
    private PropertySource<?> loadYaml(Resource path) {
        if (!path.exists()) {
            throw new IllegalArgumentException("Resource " + path + " does not exist");
        }
        try {
            return this.loader.load("custom-resource", path, null);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
        }
    }
}

spring doc

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 2020-11-09
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2015-03-11
    相关资源
    最近更新 更多