Не удалось автоматически подключить BuildProperties Spring Boot 2.1.5 и затмение - PullRequest
0 голосов
/ 17 июня 2019

Я создаю очень простое приложение с несколькими API REST, и в настоящее время оно работает правильно, пока я не попытаюсь использовать BuildProperties в моем API проверки работоспособности. При запуске приложения я получаю следующую ошибку:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-17 09:54:29.210 ERROR 10796 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field buildProperties in com.controller.HealthCheck required a bean of type 'org.springframework.boot.info.BuildProperties' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
    - Bean method 'buildProperties' in 'ProjectInfoAutoConfiguration' not loaded because @ConditionalOnResource did not find resource '${spring.info.build.location:classpath:META-INF/build-info.properties}'


Action:

Consider revisiting the entries above or defining a bean of type 'org.springframework.boot.info.BuildProperties' in your configuration.

Я пошел к файлу сборки, я также посмотрел в файле jar, созданном сборкой, и я вижу, что build-info.properties на самом деле там. В файле jar путь к файлу «BOOT-INF \ classes \ META-INF \». У меня также есть другие элементы "Autowired", которые не имеют проблем.

Где мой код не работает:

@RestController
public class HealthCheck {

    @Autowired
    Environment environment;

    @Autowired 
    BuildProperties buildProperties;


    @GetMapping("/health")
    public HealthCheckResponse healthCheck() {
        return getHealthCheckResponse();
    }

    private HealthCheckResponse getHealthCheckResponse(){
        HealthCheckResponse healthResponse = new HealthCheckResponse();
        String[] profiles = environment.getActiveProfiles();

        healthResponse.setServerTime(new Date());
        healthResponse.setVersion(buildProperties.getVersion());
        healthResponse.setEnvironment(profiles[0]);

        return healthResponse;
    }

Мой файл сборки Gradle:

plugins {
    id 'org.asciidoctor.convert' version '1.5.3'
    id 'org.springframework.boot' version '2.1.5.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'
apply plugin: 'eclipse'
apply plugin: 'java'

group = 'com'
version = '0.0.1'
sourceCompatibility = '12'

repositories {
    mavenCentral()
}

ext {
    set('snippetsDir', file("build/generated-snippets"))
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-jersey'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:2.1.1'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.restdocs:spring-restdocs-webtestclient'
    testImplementation 'org.springframework.security:spring-security-test'
}

test {
    outputs.dir snippetsDir
}

asciidoctor {
    inputs.dir snippetsDir
    dependsOn test
}

springBoot {
    buildInfo()
}

build-info.properties:

#Properties
#Mon Jun 17 10:52:04 EDT 2019
build.version=0.0.1
build.group=com
build.name=app
build.artifact=app
build.time=2019-06-17T14\:52\:04.829909200Z

Ответы [ 3 ]

0 голосов
/ 17 июня 2019

Как подсказал @Borislav Markov, я попытался запустить его через командную строку, и он, кажется, работает отлично, независимо от того, использую ли я JDK 12 или JDK 8. Я думаю, что проблема связана с плагином eclipse, который я использую для запуска приложения черезIDE.

0 голосов
/ 17 июня 2019

Я думаю, что ваша IDE смущена тем фактом, что «толстая банка» перезаписывает обычную банку. Среда понимает путь к классу обычного сгенерированного jar + ресурса `build-info.properties.

Я всегда собираю фляги под разными именами, поэтому я могу избежать подобных проблем с частичными сборками.

https://docs.spring.io/spring-boot/docs/current/gradle-plugin/reference/html/#packaging-executable-and-normal

Чтобы избежать записи исполняемого архива и обычного архива в одно и то же местоположение, один или другой должен быть настроен для использования в другом месте. Один из способов сделать это - настроить классификатор:

bootJar {
    classifier = 'boot'
}
0 голосов
/ 17 июня 2019

Я бы предложил попробовать запустить под JDK 8 и запустить из командной строки с java -jar <your jar name> только для того, чтобы убедиться, что вы правильно установили свойства сборки.

Возможно, Jdk 12 пока не подходит для весенней загрузки. Я думаю, что у вас могут быть и другие проблемы. Многие платформы Java не сертифицированы на 100%, что они будут работать с JDK 12.

Я думаю, что планируется официально поддерживать Java 12 начиная с Spring Boot 2.2

...