Spring boot 使用@Value访问Spring Boot 2.0中的buildInfo
之前在SpringBoot1.x中,我编写了一个Gradle任务,将jar的构建版本复制到应用程序的Spring boot 使用@Value访问Spring Boot 2.0中的buildInfo,spring-boot,spring-boot-gradle-plugin,Spring Boot,Spring Boot Gradle Plugin,之前在SpringBoot1.x中,我编写了一个Gradle任务,将jar的构建版本复制到应用程序的application.yml,并用正则表达式替换给定的属性,例如info.build.version:0.0.1 迁移到Spring Boot 2.0,我意识到有一个io.Spring.dependency management插件允许我定义buildInfo任务: springBoot { buildInfo() } 当访问/info执行器时,该功能工作并成功显示相同的信息 现在我想
application.yml
,并用正则表达式替换给定的属性,例如info.build.version:0.0.1
迁移到Spring Boot 2.0,我意识到有一个io.Spring.dependency management
插件允许我定义buildInfo
任务:
springBoot {
buildInfo()
}
当访问/info
执行器时,该功能工作并成功显示相同的信息
现在我想在两个用例中使用META-INF/build-info.properties中生成的build.version
:
在SwaggerUI中显示版本
在每个日志行中包括版本
以前,这样访问属性就足够了:@Value(${info.build.version:undefined}”)String buildVersion
或者在logbackspring.xml中:
<springProperty scope="context" name="applicationVersion" source="info.build.version"/>
如中所建议,但这似乎没有任何效果。您需要将文件META-INF/build info.properties
作为@PropertSource
添加到Spring Boot应用程序中:
@SpringBootApplication()
@PropertySource("classpath:META-INF/build-info.properties")
public class MyApp implements WebMvcConfigurer {
...
}
之后,您可以通过控制器/服务中的@Value
访问属性build.version
@Controller(...)
public MyController {
@Value("${build.version}") String myVersion;
...
}
当涉及到spring引导时
,几乎spring处理的所有信息都可以作为spring管理的bean访问
对于构建信息,springboot
有一个bean
公开用于名为buildProperties
的自动连接。这是通过projectinfo自动配置
模块实现的
除了Spring Expression language(SpEL
)对@Value
注释的支持之外,您还可以获得如下所述的预期结果
@Value("#{buildProperties.get('version')}") // not 'build.version'
private String myAppBuildVersion;
或者更好的方法是,将buildProperties
bean直接自动连接到您的组件,这样您就可以随心所欲地使用它了
@Autowired
private BuildProperties buildProperties;
注意:自动配置将删除版本。
前缀。那么你的
SpEL
表达式应使用version
作为键。不是build.version
更新:
我首先被你的问题弄糊涂了,因为问题更多的是关于如何使用@Value
注释。因此,我将保留上述答案
要帮助您使用logback spring.xml
,请将build info.properties
导入logback spring.xml
,如下所示。这使得build-info.properties中的每个键都可以使用logback placeholder
访问。(不要将其与SPRING属性占位符或SPRING表达式混淆)
[${build.version}]%d{ISO8601}%-5p[%c{3}]\(%t:%X{}\)%m%n
”资源“
标记的
属性将查看类路径资源
,并找到合适的解决方案。已经有解决方案了吗?谢谢Raja,我非常喜欢你的解决方案,我认为这是一个非常干净的解决方案。不幸的是,此设置要求存在META-INF/build-info.properties
,否则提到的bean和logback将抛出错误。编译这样的工件是没有问题的,但是一旦项目导入到MyIDE(IntelliJ)中,相应的buildInfo任务就不会运行。默认情况下,Gradle编译为build/
,而IntelliJ编译为out/
。我会接受你的回答,因为我没有要求本地开发选项。如果这是你的问题,你可以随时根据需要配置编译输出目录。。。
@Autowired
private BuildProperties buildProperties;
<?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>