使用@Value 访问 Spring 引导执行器 build.version 属性

Access Spring Boot Actuator build.version property with @Value

这应该很容易,但行不通。 我在 Spring Boot (2.0.1-RELEASE) 应用程序中激活了 spring-boot-actuator。

Actuator-Endpoint /actuator/info 按预期工作并且还显示了正确的版本信息。文件 build-info.properties 存在。

当尝试访问版本 属性 时(例如在我的 Spring-Controller-Class 中):

@Value("${build.version}) private String version;

操作失败,错误为 Could not resolve placeholder 'build.version' in value "${build.version}"

有什么建议吗?

我需要将文件 build-info.properties 添加为 @PropertSource

@SpringBootApplication()
@PropertySource("classpath:META-INF/build-info.properties")
public class MyApp implements WebMvcConfigurer { 
  [...]
}

然后就可以在注解中使用build-info了

@SomeAnnotation(value = "${build.version}")
public class someClass { ... }

使用 spring 表达式语言非常简单明了。

@Value("#{buildProperties.get('version')}")           // not 'build.version'
private String myAppBuildVersion;

或者更好的是,AutowirebuildProperties bean 直接添加到您的组件中,这样您就可以随心所欲地使用它。

@Autowired
private BuildProperties buildProperties;

NOTE: The autoconfiguration strips off the build. prefix. So your SpEL expressions should use version as key. Not build.version.

在您的@Service 中,将@Value 放入构造函数中,作为构造函数的参数。不要使用独立值并尝试引用它。

像这样:

@Service
public class myService {

  public myService(@Value("${my.param}") String myParam) {
   client.withParam(myParam).build();
  }

}

您的 application.properties 的值如下:

my.param=http://google.com

我已经尝试过其他实现方式,但它们不起作用。例如,

 @Service
 public class myService {

      @Value("${my.param}")
      String myParam;

      public myService() {
       client.withParam(myParam).build();
      }

  }

无效。

在这种情况下,服务将被初始化,但字符串将为空。我无法解释。我猜想与参数构造和 bean 初始化时间有关。