使用@Value

时间:2018-04-10 08:23:30

标签: spring-boot spring-boot-gradle-plugin

以前在Spring Boot 1.x中,我编写了一个Gradle任务,将jar的构建版本复制到应用程序的application.yml,并用regex替换给定的属性,例如: info.build.version: 0.0.1

迁移到Spring Boot 2.0,我意识到io.spring.dependency-management插件允许我定义buildInfo任务:

springBoot {
    buildInfo()
}

这可以在访问/info执行器时成功显示相同的信息。

现在我想在两个用例中使用build.version中生成的META-INF/build-info.properties

  1. 在SwaggerUI中显示版本
  2. 在每个日志行中包含该版本
  3. 以前,访问该属性就足够了:@Value("${info.build.version:undefined}") String buildVersion 或在logback-spring.xml

    <springProperty scope="context" name="applicationVersion" source="info.build.version"/>
    

    不幸的是,即使我将info.build.version替换为build.version(我希望它能够正常工作),两个访问者都不再工作了。

    我认为在logback中包含版本只需通过@Value注释访问该属性只需一小步,因此这是我的问题的核心:

    如何通过build.version访问META-INF/build-info.properties中生成的@Value

    我也尝试添加任务

    processResources {
        filesMatching('build-info.properties') {
            expand(project.properties)
        }    
    }
    

    https://stackoverflow.com/a/42051412/3105453中所述,但似乎没有任何效果。

2 个答案:

答案 0 :(得分:5)

当谈到spring-boot时,几乎每个spring处理的信息都很可能作为spring托管bean访问。

对于构建信息,spring-boot有一个bean公开用于自动装配,名为buildProperties。这通过ProjectInfoAutoConfiguration模块发生。

与Spring Expression语言( SpEL )一起支持@Value注释,您可以获得如下所述的预期结果。

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

或者更好的是,将buildProperties bean直接自动装配到您的组件,以便您可以随意使用它。

@Autowired
private BuildProperties buildProperties;
  

注意:自动配置会删除build.前缀。所以你的   SpEL表达式应使用version作为关键字。不是build.version

<强>更新

我首先对你的问题感到困惑,因为问题更多的是关于如何使用@Value注释。所以我将保留上述答案。

为了帮助您使用logback-spring.xml,请将build-info.properties导入logback-spring.xml,如下所示。这允许使用logback place-holders访问build-info.properties中的每个键。 (请勿使用弹簧属性演员或弹簧表达式进行混淆)

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <springProperty scope="context" name="appLogTarget" source="app.log.target"
    defaultValue="CONSOLE"/>
  <property resource="META-INF/build-info.properties" />


  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.classic.PatternLayout">
      <Pattern>[${build.version}] %d{ISO8601}" %-5p [%c{3}"] \(%t:%X{}"\) %m%n</Pattern>
    </layout>
  </appender>
 <root>
    <level value="DEBUG"/>
    <appender-ref ref="CONSOLE"/>
  </root>
</xml>

"resource"标记的<properties/>属性将查看classpath resources并找到合适的属性。

答案 1 :(得分:1)

您需要将文件META-INF/build-info.properties添加为@PropertSource到Spring-Boot-Application:

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

之后,您可以通过控制器/服务/中的build.version访问媒体资源@Value

@Controller(...)
public MyController {
    @Value("${build.version}") String myVersion;
    ...
}