You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置同时加载多个message properties资源配置文件

多properties配置文件加载实现方案

分不同项目场景提供可直接落地的实现方式:

普通Java原生项目实现

直接通过JDK自带的Properties类先后加载多个配置文件即可,重复key默认后加载的覆盖先加载的,可自行调整加载顺序:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MultiPropertiesLoader {
    public static void main(String[] args) {
        Properties allProps = new Properties();
        // 从类路径下加载两个配置文件
        try (
            InputStream msgIn = MultiPropertiesLoader.class.getClassLoader().getResourceAsStream("messages.properties");
            InputStream handleIn = MultiPropertiesLoader.class.getClassLoader().getResourceAsStream("handle.properties")
        ) {
            allProps.load(msgIn);
            allProps.load(handleIn);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 直接通过getProperty读取任意配置里的key
        System.out.println(allProps.getProperty("test.key"));
    }
}

注意:要确保两个配置文件已经被正确编译到类路径下,加载时文件名大小写要和实际文件完全一致

Spring/Spring Boot 项目实现

注解方式(推荐)

在配置类上添加多个@PropertySource注解指定配置文件路径:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = "classpath:messages.properties", encoding = "UTF-8")
@PropertySource(value = "classpath:handle.properties", encoding = "UTF-8")
public class CustomPropertiesConfig {
    // 后续在Spring管理的Bean中直接用@Value("${key名}")即可注入对应值
}

如果存在同key需要优先加载某个配置的需求,调整@PropertySource的顺序即可,后面加载的配置优先级更高。

配置文件导入方式(Spring Boot专属)

直接在项目默认的application.properties或application.yml中添加导入配置:

spring.config.import=classpath:messages.properties,classpath:handle.properties

导入后直接用@Value或@ConfigurationProperties读取配置即可。

XML配置方式(传统Spring MVC项目)

如果是用XML配置的Spring项目,可直接配置PropertyPlaceholderConfigurer加载多个文件:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:messages.properties</value>
            <value>classpath:handle.properties</value>
        </list>
    </property>
    <property name="fileEncoding" value="UTF-8"/>
</bean>

内容的提问来源于stack exchange,提问作者Ikaro Sales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:48:03