spring boot 中使用 maven 资源过滤器的问题

1,529 阅读2分钟

一. 概述

在上一篇文章 maven基础知识总结 中描述了如下内容:通过 <filtering>true</filtering> 开启过滤器功能,开启之后就可以从 pom.xml 文件、 <properties> 元素或者 <filters> 中指定的 properties 文件中读取变量的值替换 ${变量名}

但是在 spring boot 中无法通过  ${变量名} 定义变量,应该使用 @变量名@

通过查看 spring-boot-starter-parent 中的 pom.xml 文件,有如下内容:

image.png

image.png

二. 在 spring boot 中使用自定义的配置文件

下面通过一个例子来说明上面的功能,定义一个 hello.txt 文件,文件中通过 @变量名@ 方式定义一些变量,用来验证变量替换的功能,定义了 test.txt 用来验证文件排除功能,定义了一个 my.properties 文件指定变量的值,如下图所示:

image.png

其中 spring boot 项目的 pom.xml 文件有如下内容:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        
            <!--使用 <excludes> 排除 src/main/resources 目录下的 test.txt 文件 -->
            <excludes>
                <exclude>test.txt</exclude>
            </excludes>

            <!--
            开启过滤器功能,开启之后就可以从 <properties> 元素
            或者下面 <filters>中指定的 properties 文件中读取变量的值
            替换 ${变量名} 
            -->
            <filtering>true</filtering>
        </resource>
    </resources>
    <filters>
        <filter>src/main/resources/my.properties</filter>
    </filters>
</build>

使用 mvn clean package 命令打包,在 target/classes 目录可以看到 test.txt 文件被排除, @变量名@ 也被替换为指定的值,如下图所示:

image.png

三、spring-boot-starter-parent.pom 中的 resources 说明

查看 spring-boot-starter-parent.pom 有如下图所示的内容:

image.png

一开始并没有看懂这里定义的两个类似的 resource 的意思,但是仔细阅读上述的内容我们就可以明白,下面做一个简单的说明:

第一个 <resource> 配置说明:在 src/main/resources 目录包括子目录下,对 application*.ymlapplication*.yaml 以及 application*.properties 这三个文件进行过滤,也就是对这三个文件中的 @变量名@ 进行替换,其他文件不进行替换。(include 是包含的意思)

第二个 <resource> 配置说明:在 src/main/resources 目录包括子目录下,对 application*.ymlapplication*.yaml 以及 application*.properties 这三个文件不进行过滤,但是其他文件也是资源文件,它们不会被过滤,其他文件会被引入到 target 目录。(exclude 是排除的意思)

经过测试,如果项目继承自 spring-boot-starter-parent 并且在 pom.xml 文件中重新定义了 <resource> 的配置,那么 spring-boot-starter-parent 中定义的 <resource> 不会生效。