无法使用@Value在Spring应用程序中获取Maven project.version属性 [英] Cannot get maven project.version property in a Spring application with @Value
问题描述
如何在带有@Value批注的Spring Boot应用程序中获取maven project.version属性?
How to get the maven project.version property in a Spring Boot application with a @Value annotation?
推荐答案
在对如何在SpringBoot应用程序中获取Maven项目版本进行了一些研究和试验之后,我找不到适合我的任何东西.
After some research and trials on how to get the Maven project version in a SpringBoot application I couldn't find anything working for me.
由于类加载器的问题,使用清单肯定是一条烂路,即,一个清单是Spring发现的第一个清单,在我的情况下不是我的应用程序.
Using a manifest is definitively a rotten path due to class loaders issues, i.e. one gets the first manifest Spring finds, which in my case was not the one of my application.
我发现的一个解决方案是使用Maven资源插件来过滤"(替换)资源文件中的属性.在这种情况下,Spring application.properties
.
One solution I have found is to use the maven resources plugin to "filter" (replace) properties in resource files. In this case the Spring application.properties
.
下面是完成这项工作的步骤.
Below are the steps to make this work.
在pom文件中,使用以下定义激活资源过滤:
In the pom file, activate resources filtering with the following definition:
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
在application.properties
文件中:
application.name=@project.artifactId@
build.version=@project.version@
build.timestamp=@timestamp@
注意application.properties
文件中的@ property @而不是$ {property}..
Notice the @property@ instead of ${property}. in the application.properties
file.
spring-boot-starter-parent
pom将标准${}
分隔符重新定义为@
:
The spring-boot-starter-parent
pom redefines the standard ${}
delimiter as @
:
<resource.delimiter>@</resource.delimiter>
<!-- delimiter that doesn't clash with Spring ${} placeholders -->
<delimiters>
<delimiter>${resource.delimiter}</delimiter>
</delimiters>
然后可以使用@Value
这样在Spring中访问这些属性:
One can then access those properties in Spring using @Value
like this:
@Value("${application.name}")
private String applicationName;
@Value("${build.version}")
private String buildVersion;
@Value("${build.timestamp}")
private String buildTimestamp;
这篇关于无法使用@Value在Spring应用程序中获取Maven project.version属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!