繁体   English   中英

如何加载外部属性文件并覆盖springboot application.properties(没有运行时参数)?

[英]How to load external properties file and override springboot application.properties (without runtime args)?

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

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

但寻找更容易和 spring 引导管理的解决方案

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

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;
}

您可以使用 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 文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM