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

Spring Boot启动时通过VM选项引用Jar包内资源文件的方法

Spring Boot 启动时通过VM选项引用Jar包内resources目录文件的实现方法

1. 明确资源在Jar中的路径

resources目录下的文件编译后会被打包到Jar的根目录下,比如resources/config.properties对应Jar内的路径为/config.properties,如果是子目录如resources/sub/log.xml,对应路径为/sub/log.xml。

2. 配置VM启动参数

启动Spring Boot Jar时,添加VM参数传递资源路径,格式如下:

java -Dcustom.resource.path=/config.properties -jar your-spring-boot-app.jar

如果是子目录下的文件,参数改为:

java -Dcustom.resource.path=/sub/log.xml -jar your-spring-boot-app.jar

3. 在代码中读取指定资源

方式一:借助Spring的ResourceLoader

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ResourceReader {

    @Autowired
    private ResourceLoader resourceLoader;

    public void loadSpecifiedResource() throws IOException {
        // 从VM参数中获取资源路径
        String resourcePath = System.getProperty("custom.resource.path");
        // 通过classpath前缀加载Jar内资源
        Resource resource = resourceLoader.getResource("classpath:" + resourcePath);
        
        // 读取资源流
        try (InputStream inputStream = resource.getInputStream()) {
            // 这里编写资源内容的处理逻辑,比如读取配置、解析文件等
        }
    }
}

方式二:直接使用ClassPathResource

import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;

public class SimpleResourceReader {

    public void loadResource() throws IOException {
        String resourcePath = System.getProperty("custom.resource.path");
        ClassPathResource resource = new ClassPathResource(resourcePath);
        
        try (InputStream inputStream = resource.getInputStream()) {
            // 处理资源内容
        }
    }
}

注意事项

  • VM参数中的路径不要包含classpath:前缀,代码中会统一添加;
  • 若指定的资源不存在,代码会抛出IOException,需添加异常捕获和处理逻辑;
  • Jar内的资源无法通过系统绝对路径访问,必须使用classpath方式读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:50:41