问题描述
我试图使用Spring Boot和Gradle在Java主应用程序中访问构建信息值,例如 version
。
I am trying to get access to build info values such as version
in my Java main application using Spring Boot and Gradle.
我找不到有关如何配置
-
build.gradle的任何文档/示例。
-
application.yml
(如果需要) -
Java主类
build.gradle
application.yml
(if required)Java main class
有人可以帮助上面的一个小代码示例吗文件。
could someone please help with a small code example for the above files.
在我的 build.gradle
文件中,我将拥有版本
条目,那么如何使用Spring Boot和Gradle将其导入Java主类。
In my build.gradle
file I will have the version
entry, so how to get this into Java main class using Spring Boot and Gradle.
version=0.0.1-SNAPSHOT
I已经尝试添加
apply plugin: 'org.springframework.boot'
springBoot {
buildInfo()
}
,但 buildInfo( )
在Intellij中未被识别为关键字
but the buildInfo()
isn't recognised as a keyword in Intellij
在我的Java主类中,我有以下内容:
In my Java main class I have the following:
public class MyExampleApplication implements CommandLineRunner {
@Autowired
private ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(MyExampleApplication.class, args);
}
@Override
public void run(String[] args) throws Exception{
Environment env = (Environment) context.getBean("environment");
displayInfo(env);
}
private static void displayInfo(Environment env) {
log.info("build version is <" + env.getProperty("version")
}
但是当我运行此命令时- env.getProperty(版本)
显示为 null
。
But when I run this - the output from env.getProperty("version")
is showing as null
.
推荐答案
Spring Boot使用 buildInfo()
生成的信息自动配置 BuildProperties
bean。
Spring Boot auto-configures a BuildProperties
bean with the information generated by buildInfo()
.
因此要获取信息,请使用 context.getBean(BuildProperties.class).getVersion();
。
So to get the information use context.getBean(BuildProperties.class).getVersion();
.
这篇关于如何使用Gradle和Spring Boot捕获构建信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!