比如我们在pom中配置了一些属性,希望可以直接读取到yml里面作为配置使用。
<artifactId>config-center</artifactId>
<packaging>jar</packaging>
<properties>
<application.name>test</application.name>
</properties>
下面我们在yaml直接使用 @xx@ 来读取pom中的配置。
spring:
application:
name: @application.name@
profiles:
active: native
cloud:
nacos:
discovery:
server-addr: localhost:8848
如果报错:
org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character ‘@’ that cannot start any token. (Do not use @ for indentation)
in ‘reader’, line 8, column 11:
name: @application.name@
表示缺少一些maven插件,一般加入下面的插件即可解决:
<build>
<!--指定filtering=true.maven的占位符解析表达式就可以用于它里面的文件-->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!--支持yaml读取pom的参数-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<encoding>UTF-8</encoding>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
properties中使用pom中的变量。
在properties中获取pom中项目版本号:
app.version=${project.version}
在maven中获取编译时间戳
在 pom文件properties 中添加两个属性:
<properties>
<!--maven.build.timestamp保存了maven编译时间戳-->
<timestamp>${maven.build.timestamp}</timestamp>
<!--指定时间格式-->
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
</properties>
在pom中增长(使用maven渲染yml)
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
在application.yml中配置:
app:
build:
time: @timestamp@
同理,在properties文件中配置:
app.build.time=${timestamp}
本文介绍如何在Maven项目中使用YAML文件,并实现从POM文件中读取属性值进行配置。通过配置Maven插件和启用资源过滤功能,可以轻松地将POM属性注入到YAML配置中,同时提供了获取编译时间戳的方法。

被折叠的 条评论
为什么被折叠?



