基于Maven的约定大于配置的原则,我们的项目只要按照约定的规范就可以在pom文件中无需编写资源文件的配置工作就可以正确的将资源文件打包到正确的位置而不会出现找不到资源文件的情况。然后对于特殊的一些情况,如资源文件放置在java文件的目录下的情况,就必须对pom进行特殊的配置才能使得资源文件在项目运行时被正确读取。
如下项目结构:
test.properties资源文件被放在了java目录com/delorean/grizzly/exception下,对于这样的代码结构,Maven的默认打包方式是不会将其打包至目标中的。
正确配置可以使Maven感知到该资源文件的存在:
<resources>
<resource>
<directory>src/main/java/com/delorean/grizzly/exception</directory>
<filtering>false</filtering>
<includes>
<include>test.properties</include>
</includes>
</resource>
</resources>
然而通过运行发现test.properties最终在打包时被放置在classes目录下,使得java代码仍然无法找到该文件,其正确的路径应该是在classes/com/delorean/grizzly/exception目录下,这就需要在pom中增加一行配置,指定文件的输出目的地。
<resources>
<resource>
<directory>src/main/java/com/delorean/grizzly/exception</directory>
<filtering>false</filtering>
<includes>
<include>test.properties</include>
</includes>
<strong><span style="color:#ff0000;"><targetPath>com/delorean/grizzly/exception</targetPath></span></strong>
</resource>
</resources>
重新运行pom会发现test.properties文件已经在正确的输出位置了。
另外,对于在resources目录下的部分资源文件我们根据不同的打包方案可能在部分文件之间进行取舍,这时就需要另外的配置了。
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<strong><span style="color:#ff0000;"><filtering>false</filtering></span></strong>
<excludes>
<span style="color:#ff0000;"><strong><exclude>test/test.properties</exclude></strong></span>
</excludes>
</resource>
</resources>
这里特别要注意的是<filtering>元素必须要加以配置,否则整个<resource>节点的配置都将无效。
这段配置作用是排除resources目录下的test下的test.properties文件。
也可以使用<include>配置要包含的列表。