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
相关产品推荐
相关产品推荐

