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

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

1.1、问题描述

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

1.2、pom里边添加如下配置

<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、修改加载资源文件的方式

// 加载资源文件方式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();

 

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在将Spring Boot项目打成jar包后,如果工具类无法读取模板文件,可能是因为模板文件没有被正确地打包进jar包中。这可以通过以下方法解决: 1. 确认模板文件的路径和位置。在Spring Boot项目中,模板文件通常位于/resources/templates目录下。确保文件名和相对路径都正确。 2. 使用Maven插件来打包项目。例如,在pom.xml文件中添加以下配置: ``` <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <executable>true</executable> </configuration> </plugin> </plugins> </build> ``` 3. 将模板文件的位置和路径添加到ResourceLoader中。例如,可以在工具类中使用以下代码来获取模板文件: ``` ResourceLoader resourceLoader = new FileSystemResourceLoader(); Resource resource = resourceLoader.getResource("classpath:/templates/template.html"); ``` 其中,classpath:/templates/template.html是模板文件的相对路径。 4. 如果仍然无法读取模板文件,可以尝试将模板文件打包到jar包的根目录下。在pom.xml文件中添加以下配置: ``` <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> <filtering>true</filtering> </resource> </resources> </build> ``` 这将在打包时将src/main/resources目录下的所有文件打包到根目录下。 综上所述,将Spring Boot项目打包成jar包后,如果工具类无法读取模板文件,需要注意模板文件的路径和位置,并使用Maven插件来打包项目。此外,还可以将模板文件打包到jar包的根目录下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值