系列二十九、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();
相关推荐
_qingche3 分钟前
H2 数据库到 MySQL 数据迁移
java·数据库·spring boot·mysql·spring·重构·kotlin
码语智行3 小时前
系统启动时初始化数据功能分析
java·spring boot
invicinble3 小时前
推荐一下,遇到的几本比较好的书
spring boot
憧憬成为java架构高手的小白4 小时前
git工作流程简化版
java·spring boot·git
YDS8295 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— 动态决策策略的接口对接
java·spring boot·ai·agent·spring ai·deepseek
淘源码A5 小时前
专科医院云HIS系统源码:技术栈包括SpringBoot、Angular、MySQL等
spring boot·后端·源码·云his·医院信息系统·医院his系统
小马爱打代码5 小时前
基于 SpringBoot 的微服务文件上传下载组件设计与实现
spring boot·后端
Java患者·7 小时前
Spring Boot 3 整合 Elasticsearch 8
spring boot·后端·elasticsearch