无法使用 @Value 在 Spring 应用程序中获取 maven project.version 属性 [英] Cannot get maven project.version property in a Spring application with @Value

查看:72
本文介绍了无法使用 @Value 在 Spring 应用程序中获取 maven project.version 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在带有@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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆