经过一些关于如何在 SpringBoot 应用程序中获取 Maven 项目版本的研究和试验后,我找不到任何适合我的东西。
由于类加载器问题,使用清单绝对是一条糟糕的路径,即获得 Spring 找到的第一个清单,在我的情况下,这不是我的应用程序的清单。
我发现的一种解决方案是使用 Maven 资源插件来“过滤”(替换)资源文件中的属性。在这种情况下,春天application.properties
.
以下是实现此目的的步骤。
在 pom 文件中,使用以下定义激活资源过滤:
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
In the application.properties
file:
[email protected] /cdn-cgi/l/email-protection@
[email protected] /cdn-cgi/l/email-protection@
build.timestamp=@timestamp@
请注意 @property@ 而不是 ${property}。 in the application.properties
file.
The spring-boot-starter-parent
pom重新定义标准${}
分隔符为@
:
<resource.delimiter>@</resource.delimiter>
<!-- delimiter that doesn't clash with Spring ${} placeholders -->
<delimiters>
<delimiter>${resource.delimiter}</delimiter>
</delimiters>
然后可以使用 Spring 访问这些属性@Value
像这样:
@Value("${application.name}")
private String applicationName;
@Value("${build.version}")
private String buildVersion;
@Value("${build.timestamp}")
private String buildTimestamp;
此处提供了示例项目 https://bitbucket.org/JackG/maven-properties-at-runtime.