Spring 能否在类路径中支持多个 messages.properties 文件?

Can Spring support multiple messages.properties files in classpath?

有一个 JAR A 和 JAR B,在类路径 /

中都有 messages.properties

还有 WAR C,它依赖于 JAR A 和 JAR B。

当我启动 WAR C 时,我只能从 JAR A 或 JAR B 获取 i18n 消息。

那么,Spring 如何在类路径中支持多个 messages.properties 文件?

顺便说一句,WAR C 是一个 spring 引导项目,spring.messages.basename=messages

是的,Spring支持加载多个属性。但是属性应该是唯一的。如果我们在两个属性文件中具有相同的属性,那么稍后加载的文件将覆盖前一个文件中的前一个属性。

例如,如果 JAR A 中的属性文件有两个属性 {USERNAME, PASSWORD} 并且 JAR B 属性文件也有相同的两个属性,那么您将从正在加载的文件中获取 {USERNAME, PASSWORD}稍后。

您可以使用通配符导入类路径中所有 属性 个同名文件。

在Spring中可以用Array的形式提及不同的Properties文件如下:

<context:property-placeholder
location="classpath:war.properties,
          classpath*:message.properties"
ignore-unresolvable="true"/>

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:war.properties</value>
            <value>classpath*:message.properties</value>
        </list>
    </property> 
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

问题已解决。

根据这个问题Does Spring MessageSource Support Multiple Class Path?

have to ditch ResourceBundleMessageSource and write a custom implementation of MessageSource (most likely by subclassing AbstractMessageSource) which uses PathMatchingResourcePatternResolver to locate the various resources and expose them via the MessageSource

我复制了一份 ReloadableResourceBundleMessageSource 并按照本指南编写代码并解决了问题。