自定义 Maven 占位符

本文将介绍怎样自定义 Maven 占位符

在 Maven 中,默认使用 ${} 作为占位符。下面将演示在 Spring Boot 项目中,通过 ${} 占位符来引用 pom.xml 文件中 <profile> 标签下面 <properties> 标签中定义的数据。pom.xml 部分配置如下:

<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <jdbc.url>jdbc:mysql://localhost:3306/test</jdbc.url>
            <jdbc.driver>com.mysql.jdbc.Driver</jdbc.driver>
            <jdbc.username>root</jdbc.username>
            <jdbc.password>aaaaaa</jdbc.password>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>

Spring Boot 的 application.properties 文件配置如下:

jdbc.driver=${jdbc.driver}
jdbc.url=${jdbc.url}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}

然后,使用 maven 的 package 声明周期打包,你会发现并没有替换成功。这是为什么呢?(点击查看Spring Boot 引用 Maven ${} 占位符无效)这是因为 Spring Boot 使用插件将 maven 占位符替换成了 “@variable_name@”。因此将 Spring 的 application.properties 文件修改如下:

jdbc.driver=@jdbc.driver@
jdbc.url=@jdbc.url@
jdbc.username=@jdbc.username@
jdbc.password=@jdbc.password@

再次执行 maven 的 package 命令,替换成功了。结果如下:

jdbc.driver=co.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=aaaaaa

自定义 maven 占位符

前面提到的都是 Maven 或者 Spring Boot 的默认行为,我们还可以根据自己的喜好定义不同的占位符。这就需要借助 maven-resources-plugin 插件了,如果你要了解该插件的详细信息,请访问 http://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html 地址。

在 pom.xml 文件中,添加 maven-resources-plugin 插件的依赖,配置如下:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <useDefaultDelimiters>false</useDefaultDelimiters>
        <delimiters>
            <delimiter>$[*]</delimiter>
        </delimiters>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>

上面配置中,使用 <useDefaultDelimiters> 禁用默认占位符分隔符,使用 <delimiters> 元素定义自己的占位符分隔符。占位符分割符号格式为 “开始*结束”,如果占位符分隔符开始和结束字符一致,可以简化为 “分割符”。例如:“@*@” 和 “@” 等价。插件官方原文说明:

Set of delimiters for expressions to filter within the resources. These delimiters are specified in the form beginToken*endToken. If no * is given, the delimiter is assumed to be the same for start and end.

So, the default filtering delimiters might be specified as:

<delimiters>
  <delimiter>${*}</delimiter>
  <delimiter>@</delimiter>
</delimiters>

Since the @ delimiter is the same on both ends, we don't need to specify @*@ (though we can).

配置好 maven-resources-plugin 插件后,我们去修改一下 application.properties 文件,内容如下:

jdbc.driver=${jdbc.driver}
jdbc.url=${jdbc.url}
jdbc.username=@jdbc.username@
jdbc.password=$[jdbc.password]

执行 maven 的 package 命令,输出结果如下:

jdbc.driver=${jdbc.driver}

jdbc.url=${jdbc.url}

jdbc.username=@jdbc.username@

jdbc.password=aaaaaa

上面结果中,只有最后一行被成功替换了,因为我们禁用了默认占位符分割符,使用 $[] 作为自定义的分隔符。

最困难的事情就是认识自己。——希腊
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号