如何在 Spring 中让 @PropertyResource 优先于任何其他 application.properties? [英] How to give @PropertyResource precedence over any other application.properties in Spring?

查看:17
本文介绍了如何在 Spring 中让 @PropertyResource 优先于任何其他 application.properties?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在类路径之外添加外部配置属性资源.它应该覆盖任何现有的属性.

I'm trying to add an external configuration property resource outside of the classpath. It should override any existing properties.

但以下方法不起作用:

@SpringBootApplication
@PropertySource("d:/app.properties")
public class MyClass extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyClass .class);
    }

    @Value("${my.property}")
    private String myprop;

    @PostConstruct
    public void init() {
        Sysout(myprop);
    }
}

src/main/resources/application.properties:

src/main/resources/application.properties:

my.property=internal

d:/app.properties:

d:/app.properties:

my.property=external

启动应用时的结果:内部

为什么?

推荐答案

你不能.@PropertySource 处理有 明确定义的优先顺序.您可以使用 EnvironmentPostProcessor 以任何方式自定义环境.

You can't. @PropertySource handling has a well defined precedence order. You can customize the environment any way you want with an EnvironmentPostProcessor.

我们在 Devoxx 演示文稿中解释了该用例,请参阅演示文稿的这一部分 了解更多详情.你也可以 在线查找代码示例.

We explain that use case in a Devoxx presentation, please refer to this section of the presentation for more details. You can also find the code sample online.

特别是,您会发现如果您使用 addFirst,您的自定义 PropertySource 将优先于所有内容.但是您也可以实现您的 EnvironmentPostProcessor,以便命令行参数或系统属性仍然覆盖这些值.我觉得这很有用,但您的用例可能有所不同.

In particular, you'll find that if you use addFirst your custom PropertySource will have precedence over everything. But you could also implement your EnvironmentPostProcessor so that command line arguments or system properties still override those values. I find that useful but your use case may differ.

这篇关于如何在 Spring 中让 @PropertyResource 优先于任何其他 application.properties?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆