You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.0.1中@Value获取Actuator的build.version属性失败求助

解决Spring Boot中@Value无法获取build.version的问题

我之前也碰到过一模一样的问题——Actuator的/actuator/info能正常显示版本信息,但用@Value("${build.version}")就是拿不到,报占位符解析失败的错误。其实核心原因是:Spring Boot默认不会把build-info.properties里的属性加载到Spring环境中,Actuator是单独读取这个文件来生成info接口内容的,和@Value依赖的Environment不是一回事。

下面是几个可行的解决办法,按推荐程度排序:

1. 用BuildProperties类注入(最优雅)

Spring Boot专门提供了BuildProperties类来封装build-info的所有属性,完全不用自己写@Value。直接注入这个类就行:

import org.springframework.boot.info.BuildProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VersionController {

    private final BuildProperties buildProperties;

    // 构造注入或者@Autowired都可以
    @Autowired
    public VersionController(BuildProperties buildProperties) {
        this.buildProperties = buildProperties;
    }

    @GetMapping("/version")
    public String getVersion() {
        return buildProperties.getVersion();
        // 还能拿其他属性,比如build时间、groupId等
        // buildProperties.getTime()、buildProperties.getGroup()
    }
}

这个方法的好处是Spring Boot已经帮你处理了文件加载逻辑,不用担心路径或者配置问题,只要你已经通过spring-boot-maven-plugin生成了build-info.properties(你已经有这个文件了),这个类就会自动被创建。

2. 手动将build-info.properties加载到Environment

如果一定要用@Value,可以在配置类或者主启动类上添加@PropertySource注解,指定文件路径:

import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@PropertySource("classpath:META-INF/build-info.properties")
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

这样build.version就会被加载到Spring环境中,@Value("${build.version}")就能正常获取了。注意默认情况下build-info.properties是生成在META-INF目录下的,路径不要写错。

3. 先检查build-info.properties的内容

最后可以确认一下你的build-info.properties里的键名是否正确,默认maven插件生成的内容应该是这样的:

build.version=1.0.0-SNAPSHOT
build.group=com.yourcompany
build.artifact=your-project
build.name=your-project
build.time=2024-05-20T14:30:00Z

如果键名不是build.version(比如有些自定义配置可能改成了version),那@Value的表达式也要对应调整。

内容的提问来源于stack exchange,提问作者Tarator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:23:48