系列二十九、Spring Boot打成jar包后,resources目录下的资源文件获取不到

一、Spring Boot打成jar包后,resources目录下的资源文件获取不到

1.1、问题描述

在做公司业务开发时,有一个地方是使用EasyExcel模板技术进行文件上传,测试环境是OK的,但是和前后端联调验证测试通过后,上传到生产环境就不行了,后来也是花费了很多时间才找出其中的问题,以下为解决方案。

1.2、pom里边添加如下配置

XML 复制代码
<build>
	<!-- 定义包含这些资源文件,能在jar包中获取这些文件 -->
	<resources>
		<resource>
			<directory>src/main/java</directory>
			<includes>
				<include>**/*.properties</include>
				<include>**/*.xml</include>
				<include>**/*.yml</include>
			</includes>
			<!--是否替换资源中的属性-->
			<filtering>false</filtering>
		</resource>
		<resource>
			<directory>src/main/resources</directory>
			<includes>
				<include>**/*.*</include>
			</includes>
			<!--是否替换资源中的属性-->
			<filtering>false</filtering>
		</resource>
	</resources>
</build>

1.3、修改加载资源文件的方式

java 复制代码
// 加载资源文件方式1:
ClassPathResource classPathResource = new ClassPathResource("static/budgetunit/employee_budget_unit_export.xlsx");
String templatePath = classPathResource.getPath();

// 加载资源文件方式2(推荐):
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/budgetunit/employee_budget_unit_export.xlsx");
String templatePath = ClassLoader.getSystemResource("templates/budgetunit/employee_budget_unit_export.xlsx").getPath();
相关推荐
2601_953720821 小时前
【计算机毕业设计】基于Spring Boot的心理健康咨询与评测系统的设计与实现
java·spring boot·后端
whyfail3 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
Muscleheng4 小时前
Spring Boot 3.x 集成 DeepSeek 实现 Function Calling(工具调用)
人工智能·spring boot·后端·ai·spring ai·deepseek
@航空母舰4 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
IT_Octopus7 小时前
Spring Boot 中 ThreadLocal 请求上下文的完整生命周期
java·spring boot·spring
IT_Octopus9 小时前
Spring Boot 线程池关闭:destroyMethod 的作用与最佳实践
java·spring boot·后端
米码收割机10 小时前
【项目】vue3+springboot零食商城系统(源码+文档++PPT)【独一无二】
java·spring boot·后端
Full Stack Developme11 小时前
SpringBoot 整合 HikariCP 并列出参数配置清单
spring boot·后端·adb
霸道流氓气质11 小时前
SpringBoot中事务内同步处理 + 事务后异步调用外部系统的通用模式示例
java·spring boot·后端
凤山老林11 小时前
SpringBoot实战:接口参数校验与优雅处理
java·spring boot·后端