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

在Maven重打包的嵌套Jar中使用@PropertySource加载配置文件

解决Spring Boot加载依赖Jar中properties文件的问题

方案1:使用Spring Boot专属的PropertySource工厂

默认的@PropertySource无法正确识别嵌套在BOOT-INF/lib下的Jar包内的资源,需要指定Spring Boot提供的工厂类来处理:

import org.springframework.boot.context.properties.source.SpringBootResourcePropertySourceFactory;
import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@PropertySource(
    value = "classpath:some/third/party/shipped.properties",
    factory = SpringBootResourcePropertySourceFactory.class
)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

这个工厂类会利用Spring Boot的资源加载机制,正确定位到依赖Jar中的properties文件。

方案2:在启动时手动添加配置资源

如果方案1不生效,可以通过SpringApplication手动加载资源并添加到环境中:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Properties;

@SpringBootApplication
public class YourApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(YourApplication.class);
        
        // 加载依赖Jar中的properties文件
        ClassPathResource resource = new ClassPathResource("some/third/party/shipped.properties");
        Properties props = PropertiesLoaderUtils.loadProperties(resource);
        
        // 将加载的属性添加到应用环境
        app.setDefaultProperties(props);
        
        app.run(args);
    }
}

这种方式更直接,能确保资源被加载到Spring环境中。

方案3:通过配置文件指定额外资源路径

在项目的application.properties中添加以下配置,让Spring Boot自动扫描并加载指定的额外配置文件:

spring.config.additional-location=classpath:some/third/party/shipped.properties

注意:这个配置会让Spring Boot将该文件作为额外的配置源加载,优先级低于项目自身的application.properties。


内容的提问来源于stack exchange,提问作者Ti Strga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 02:22:39