Почему HATEOAS начинает создавать проблему для весенней загрузки версии> = 2.2.x во время запуска с Swagger 2.x?

Я переместил свой проект из spring-boot 2.1.9 в 2.2.0.

При запуске проекта я сталкиваюсь с нижеследующим error Сообщения.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry


Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'linkDiscoverers' defined in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]: Unsatisfied dependency expressed through method 'linkDiscoverers' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry


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

Description:


Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration 
required a single bean, but 17 were found:
- modelBuilderPluginRegistry: defined in null
- modelPropertyBuilderPluginRegistry: defined in null
- typeNameProviderPluginRegistry: defined in null
- syntheticModelProviderPluginRegistry: defined in null
- documentationPluginRegistry: defined in null
- apiListingBuilderPluginRegistry: defined in null
- operationBuilderPluginRegistry: defined in null
- parameterBuilderPluginRegistry: defined in null
- expandedParameterBuilderPluginRegistry: defined in null
- resourceGroupingStrategyRegistry: defined in null
- operationModelsProviderPluginRegistry: defined in null
- defaultsProviderPluginRegistry: defined in null
- pathDecoratorRegistry: defined in null
- apiListingScannerPluginRegistry: defined in null
- relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
- linkDiscovererRegistry: defined in null
- entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]

Что могло вызвать эту проблему?

Примечание. Я не использую HATEOAS в своем pom.xml файл.

pom.xml

<properties>
    <java.version>1.8</java.version>
    <swagger-springfox.version>2.9.2</swagger-springfox.version>
    <sonar.jacoco.execPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.execPath>
    <jasypt-spring-boot-starter>2.1.1</jasypt-spring-boot-starter>
    <logbook-spring-boot-starter>1.13.0</logbook-spring-boot-starter>
    <assertj-swagger>0.8.1</assertj-swagger>
    <jacoco-version>0.8.4</jacoco-version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-spring-web</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-core</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>

17 ответов

У меня была проблема с Swagger + HATEOAS в моем spring-boot применение.

Исправление приведено ниже (отредактируйте класс конфигурации Swagger):

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public LinkDiscoverers discoverers() {
        List<LinkDiscoverer> plugins = new ArrayList<>();
        plugins.add(new CollectionJsonLinkDiscoverer());
        return new LinkDiscoverers(SimplePluginRegistry.create(plugins));

    }
}

Мне помогла эта ссылка: https://github.com/spring-projects/spring-hateoas/issues/731

Вкратце я добавил к своим зависимостям:

<dependency>
    <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-core</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>
          Use following 2 dependency to resolve Swagger and Hateoas dependency conflict.
    
    If Spring Boot version is >= 2.2.0 the use io.springfox version 3.0.0
    
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

После использования версии 3.0.0 swagger-ui не будет работать, поэтому используйте следующую зависимость и user / swagger-ui / вместо /swagger-ui.html

          <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

Такая проблема возникает из-за новой функции Hateoas.

Если вы хотите решить эту проблему, просто вставьте следующую строку кода в файл конфигурации swagger.

@Primary
@Bean
public LinkDiscoverers discoverers() {
    List<LinkDiscoverer> plugins = new ArrayList<>();
    plugins.add(new CollectionJsonLinkDiscoverer());
    return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
}

Я думаю, это решит вашу проблему, как и мою.

Проблема, с которой я столкнулся, когда я использовал

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-dependencies</artifactId>
   <version>2.2.6.RELEASE</version>
   <type>pom</type>
   <scope>import</scope>
</dependency>
.....
.....
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

с чванством Springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

если вы посмотрите на зависимости spring hateoas, есть зависимость от spring-plugin-core с версией 2.0.0.RELEASE

<dependency>
    <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-core</artifactId>
    <version>${spring-plugin.version}</version>
</dependency> 

но использование зависимости чванства spring-plugin-core с версией 1.2.0.RELEASE.

Spring-boot имеет конфликт при создании bean-компонента, поэтому вам необходимо объединить org.springframework.plugin версия, чтобы весна увидела это, если вы выберете 2.0.0.RELEASE чванство бот сможет компилировать,

так версия 1.2.0.RELEASE будет работать для обеих зависимостей, например

 <dependency>
    <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-core</artifactId>
    <version>1.2.0.RELEASE</version>
</dependency> 

После этого вам понадобится класс конфигурации для запуска beans для swagger а также hateoas нравится:


@EnableSwagger2
@Configuration
public class SwaggerConfiguration {

    @Primary
    @Bean
    public LinkDiscoverers discoverers() {
        List<LinkDiscoverer> plugins = new ArrayList<>();
        plugins.add(new CollectionJsonLinkDiscoverer());
        return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
    }

    @Bean
    public Docket postsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("{ApplicationName}")
                .apiInfo(buildApiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo buildApiInfo() {
        Contact contact = new Contact("CompanyName", "https://company-domain.com", "mail@company.com");
        return new ApiInfoBuilder()
                .title(""{ApplicationName}"")
                .description("API Description")
                .license("license")
                .version("1.0")
                .contact(contact)
                .licenseUrl("licenseURl")
                .build();
    }
}

Попробуйте эту версию 2.6.1, я уже решаю этим способом

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

Для версии загрузки Spring 2.1.3.RELEASE пользователей, следующие зависимости отлично работают для hateoas+swagger:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-hateoas</artifactId>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>

Вы можете изменить версию так:

      <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

Я работаю с Spring Boot 2.4.1. Но вы не можете увидеть журнал конечной точки Swagger при запуске приложения Spring Boot.

Лучшее решение

Добавьте ниже код в класс SwaggerConfig

@Bean
public LinkDiscoverers discovers() {    
    List<LinkDiscoverer> plugins = new ArrayList<>();
    plugins.add(new CollectionJsonLinkDiscoverer());
    return new LinkDiscoverers(SimplePluginRegistry.create(plugins));[enter image description here][1]  
} 

Я использую springdoc-openapi и, столкнувшись с этой проблемой, похожей на упомянутую здесь:

Description:

Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration required a single bean, but 3 were found:
    - relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
    - linkDiscovererRegistry: defined in null
    - entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Я просто добавляю эту зависимость в свой файл pom

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>1.1.1.RELEASE</version>
</dependency>

надеюсь, что это может кому-то помочь

Я получал ошибку

"Ошибка создания bean-компонента с именем 'halLinkDisocoverer', определенным в ресурсе пути к классу [org/springframework/hateoas/mediatype/hal/HalMediaTypeConfiguration.class]"..

При создании веб-службы RESTful на основе гипермедиа

Удаление этой зависимости

<dependency>
     <groupId>com.jayway.jsonpath</groupId>
     <artifactId>json-path</artifactId>
     <scope>test</scope>
</dependency>

решил мою проблему.

Проверьте эту ссылку для получения дополнительных сведений. Почему я получаю сообщение об ошибке Заводской метод halLinkDisocoverer вызвал исключение в Springboot?

Как Александр Вайс ответил первым, spring-plugin-core зависимость разрешена с неправильной версией 1.2.0.RELEASE. Чтобы принудительно использовать правильный 2.0.0.RELEASE, вы должны ЛИБО исключить неправильную транзитивную зависимость и указать правильную ИЛИ закрепить (!) эту версию зависимости в вашем pom.xml. Это делается в <dependenciesManagement> блок, а не в <dependencies>блокировать. Пример для Springfox 3.0.0:

      <spring-plugin-core.version>2.0.0.RELEASE</spring-plugin-core.version>
<springfox.version>3.0.0</springfox.version>
...

<dependencyManagement>
  <dependencies>
    <!-- API Documentation -->
    <!-- Fix wrong resolved `spring-plugin-core` dependency version for springfox -->
    <dependency>
      <groupId>org.springframework.plugin</groupId>
      <artifactId>spring-plugin-core</artifactId>
      <version>${spring-plugin-core.version}</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-boot-starter</artifactId>
      <version>${springfox.version}</version>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <!-- API Documentation -->
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
  </dependency>
</dependencies>

Если ты хочешь Swagger, но может пойти на компромисс с HATEOAS, затем просто удалите зависимость HATEOAS и добавьте:

compile group: 'io.springfox', name: 'springfox-swagger-ui', version:'2.9.2'  
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'

Решили, это происходило из-за интеграции, когда Swagger + HATEOAS использовался с Spring Boot 2.2.4.RELEASE.

package com.company.springbootworks.swagger;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.hateoas.client.LinkDiscoverer;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer;
import org.springframework.http.ResponseEntity;
import org.springframework.plugin.core.SimplePluginRegistry;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public LinkDiscoverers discoverers() {
        List<LinkDiscoverer> plugins = new ArrayList<>();
        plugins.add(new CollectionJsonLinkDiscoverer());
        return new LinkDiscoverers(SimplePluginRegistry.create(plugins));

    }

    @Bean
    public Docket eDesignApi(SwaggerConfigProperties swaggerConfigProperties) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(swaggerConfigProperties))
                .enable(Boolean.valueOf(swaggerConfigProperties.getEnabled())).select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build().pathMapping("/")
                .directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(Boolean.valueOf(swaggerConfigProperties.getUseDefaultResponseMessages()))
                .enableUrlTemplating(Boolean.valueOf(swaggerConfigProperties.getEnableUrlTemplating()));
    }

    @Bean
    UiConfiguration uiConfig(SwaggerConfigProperties swaggerConfigProperties) {
        return UiConfigurationBuilder.builder().deepLinking(Boolean.valueOf(swaggerConfigProperties.getDeepLinking()))
                .displayOperationId(Boolean.valueOf(swaggerConfigProperties.getDisplayOperationId()))
                .defaultModelsExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelsExpandDepth()))
                .defaultModelExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelExpandDepth()))
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(Boolean.valueOf(swaggerConfigProperties.getDisplayRequestDuration()))
                .docExpansion(DocExpansion.NONE).filter(Boolean.valueOf(swaggerConfigProperties.getFilter()))
                .maxDisplayedTags(Integer.valueOf(swaggerConfigProperties.getMaxDisplayedTags()))
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(Boolean.valueOf(swaggerConfigProperties.getShowExtensions()))
                .tagsSorter(TagsSorter.ALPHA).supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null).build();
    }

    private ApiInfo apiInfo(SwaggerConfigProperties swaggerConfigProperties) {
        return new ApiInfoBuilder().title(swaggerConfigProperties.getTitle())
                .description(swaggerConfigProperties.getDescription()).version(swaggerConfigProperties.getApiVersion())
                .build();
    }
}

и ниже - зависимости чванства

<properties>
    <java.version>1.8</java.version>
    <swagger.version>2.9.2</swagger.version>
    <swagger-annotations.version>1.5.21</swagger-annotations.version>
    <swagger-models.version>1.5.21</swagger-models.version>
    <spring-plugin.version>2.0.0.BUILD-SNAPSHOT</spring-plugin.version>
</properties>


<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>${swagger-annotations.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>${swagger-models.version}</version>
</dependency>

Я удалил эти зависимости как обходной путь и работал:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>

пожалуйста, дайте мне знать, работает ли у вас.

Это почти последнее исправление этой проблемы.

Читайте здесь: https://github.com/springfox/springfox

Решение:

Для версии Spring Boot>= 2.2.x RELEASE с включенным HATEOAS вы должны использовать springfox-boot-starter-3.0.0 зависимость для документации Swagger API.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

Класс конфигурации Swagger:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2);
    }

}

URL для просмотра ответа Swagger JSON: http://localhost:8080/v2/api-docs

Пример снимка экрана:


URL для просмотра HTML-ответа Swagger: http://localhost:8080/swagger-ui/index.html

Пример снимка экрана:

Примечание. Удалите все остальныеspringfox зависимость для Swagger.

Так что мне действительно нужна была поддержка hateoas, и у меня возникла та же проблема. Оказалось, такое бывает, если у вас

<dependency>
  <groupId>org.springframework.hateoas</groupId>
  <artifactId>spring-hateoas</artifactId>
</dependency>

вместо того

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
Другие вопросы по тегам