从外部 messages_en.properties 覆盖 messages_en.properties 的内容

Overwrite content of messages_en.properties from an external messages_en.properties

我在类路径 (src/main/resources) 中有一个 messages_en.properties,在 jar 外有一个,在 /config 文件夹中。但是 /config 文件夹中的 messages_en.properties(content) 不会覆盖类路径中的内容,即使在添加此标记后也是如此:

spring.config.location=config/messages_en.properties

我是不是出错了,或者这在 spring 引导中根本不可能?

请注意,application.properties 在 /config 文件夹中(外部化配置)。

您正在配置 spring.config.location,用于提供外部应用程序配置 (externalized configuration) 的位置。

如果您想引用外部位置,您应该在路径前加上 file:,例如:

spring.config.location=file:config/application.properties

但是,当您使用名为 messages_en.properties 的文件时,这更有可能是 MessageSource 使用的属性文件(对于 internationalization/localization) 而不是将其用作 application.properties 文件的替代品。

您也可以通过配置 spring.messages.* 属性为这些消息配置外部位置,例如:

spring.messages.basename=file:config/messages

您不必添加语言代码 (en),因为这是 Spring 已经用于检测正确消息文件的约定。

根据调用 MessageSource 时的给定语言,它将打开 messages_en.properties 或 messages_fr.properties 或 ... 并使用 messages.properties 作为后备,如果有未找到所提供语言的 属性。

编辑:看来 MessageSourceAutoConfiguration 只针对类路径资源启动 你需要有一个默认的回退 messages.properties 。如果没有这些,它将无法工作。

但是,您仍然可以使用这些属性并使用 @ConfigurationProperties:

手动创建 MessageSource
@Bean
@ConfigurationProperties("spring.messages")
public MessageSource messageSource() {
    return new ReloadableResourceBundleMessageSource();
}