从Gradle自动装配BuildProperties bean - NoSuchBeanDefinitionException

问题描述:

我想从我的Java应用程序中从Gradle构建文件中获取版本。我遵循这里的指示;从Gradle自动装配BuildProperties bean - NoSuchBeanDefinitionException

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-build.html

的build.gradle

buildscript { 
    repositories { 
     mavenCentral() 
    } 
    dependencies { 
     classpath("org.springframework.boot:spring-boot-gradle- 
     plugin:1.5.7.RELEASE") 
    } 
} 

project.version = '0.1.0' 

apply plugin: 'java' 
apply plugin: 'war' 
apply plugin: 'idea' 
apply plugin: 'org.springframework.boot' 

springBoot { 
    buildInfo() 
} 

jar { 
    baseName = 'ci-backend' 
} 

war { 
    baseName = 'ci-backend' 
} 

repositories { 
    mavenCentral() 
} 

sourceCompatibility = 1.8 
targetCompatibility = 1.8 

dependencies { 
    compile("org.springframework.boot:spring-boot-starter-web") 
    compile("org.springframework:spring-jdbc") 
    compile("joda-time:joda-time") 

    compile("com.opencsv:opencsv:3.9") 
    compile("org.springframework.batch:spring-batch-core") 

    testCompile('org.springframework.boot:spring-boot-starter-test') 
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') 
} 

与建筑物的gradle后build-info.properties文件存在于建立/资源/主/ META-INF/build-info.properties

在我的@RestController中,我尝试自动编译构建属性bean

@Autowired 
private BuildProperties buildProperties; 

我收到以下错误;

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.info.BuildProperties' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) 
... 41 more 

我将认为BuildProperties bean被自动创建当build-info.properties存在。似乎并非如此。

+0

@Autowired private BuildProperties buildProperties;正在工作并实例化,如果“build-info”文件是由依赖管理框架生成的。 – Oleksii

上面的配置是正确的。

我在通过intellij管理的本地tomcat实例上运行war文件。在versiongroup的垃圾期间,我生成了另一个构建工件,它以某种方式被intellij损坏/保留。我必须清理构建目录并从我的运行配置中删除部署工件,重新启动intellij,然后重新构建,并重新添加工件到运行配置以解决问题。

对于构建过程中发生的事情,我不太确定具体细节,但重要的部分是上述配置是正确的。