写在前面
在SpringBoot的项目中,默认情况下资源文件放置放在src/main/resources 中,而单元测试的资源文件放在src/test/resources中。
如果部分资源文件未放在SpringBoot默认的目录下怎么办?
默认情况下源码存放资源的目录结构:
默认情况下打包后的文件目录为:
src/main/resources 与 src/test/resources 下的资源文件的使用与加载区别是什么?
A. src/main/java中的JAVA代码只能直接加载 src/main/resources 下的资源,不能直接加载 src/test/resources 下的资源;
B. src/test/java中的JAVA代码既能加载 src/test/resources 下的资源,又能加载 src/main/resources 下的资源,当两个 resources 下都有要加载的同名资源时候,优先选择 src/test/resources 下的资源。
解决方案
方案①: 使用<resources> 标签
重新指明资源文件位置 (所有需要被打包都需要指定,并不是只指定非默认目录下的资源)
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<!-- 重新指明资源文件位置 (所有需要被打包都需要指定,并不是只指定非默认目录下的资源) -->
<resources>
<resource>
<directory>src/test/resources</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<!-- 其中 **/*.xml 这样的写法,是为了保证各级子目录下的资源文件被打包。 -->
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
方案②: 使用MAVEN-RESOURCES-PLUGIN插件
使用MAVEN-RESOURCES-PLUGIN, 将未在默认资源目录下的资源打进包中, 默认资源目录下的资源无需指定能够自动被打包。
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 使用MAVEN-RESOURCES-PLUGIN, 将未在默认资源目录下的资源打进包中, 默认资源目录下的资源无需指定能够自动被打包-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-other-resources</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>${basedir}/src/test/resources</directory>
<excludes>
<exclude>banner.txt</exclude>
</excludes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>