【问题标题】:Access Spring Boot Actuator build.version property with @Value使用 @Value 访问 Spring Boot Actuator build.version 属性
【发布时间】:2018-10-15 15:39:15
【问题描述】:

这应该很容易,但行不通。 我在我的 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}"。

有什么建议吗?

【问题讨论】:

    标签: java spring spring-boot spring-boot-actuator


    【解决方案1】:

    使用spring表达式语言非常简单干净。

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

    或者更好的是,Autowire buildProperties bean 直接添加到您的组件中,这样您就可以随意使用它了。

    @Autowired
    private BuildProperties buildProperties;
    

    注意:autoconfiguration 去掉了 build. 前缀。所以你的 SpEL 表达式应使用 version 作为键。不是build.version。

    【讨论】:

    • 谢谢!这是要走的路,并按预期工作。
    【解决方案2】:

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

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

    然后你可以在注解中使用构建信息

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

    【讨论】:

      【解决方案3】:

      在你的@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 初始化时间有关。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-01
        • 1970-01-01
        • 2016-12-27
        • 2020-09-15
        • 1970-01-01
        • 2017-09-10
        • 2019-01-08
        • 1970-01-01
        相关资源
        最近更新 更多