Подтвердить что ты не робот

Невозможно вызвать swagger-ui из приложения spring -boot

У меня есть приложение загрузки spring, которое я запускаю с помощью встроенного сервера tomcat. Я частично добился успеха в интеграции Springfox-swagger с приложением. Если я делаю /v2/api-docs, я могу видеть всю документацию обо всех api в webapp. Однако, когда я пытаюсь получить доступ к тому же из пользовательского интерфейса, он не работает. Ниже приведены подробные результаты.

Выход - localhost: 8080/api/swagger-resources

[ {
  "name" : "default",
  "location" : "/v2/api-docs",
  "swaggerVersion" : "2.0"
} ]

Выход - localhost: 8080/api/v2/api-docs

I get valid results. I can confirm that and the output is too large to paste here

Но когда я пытаюсь получить доступ к swagger-ui, это не сработает. Ниже приведены различные URL, которые я вызывал для доступа к swagger-ui.

http://localhost:8080/swagger-ui.html - UI is loading, but no documentation of API is present
http://localhost:8080/api/swagger-ui.html  - 404 Not Found
http://localhost:8080/springfox - 404 Not Found
http://localhost:8080/api/springfox - 404 Not Found

Ниже мой класс SwaggerConfig.java

package com.vmware.vrack.lcm;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                "My Project REST API",
                "This is a description of your API.",
                "version-1",
                "API TOS",
                "[email protected]",
                "API License",
                "API License URL"
        );
        return apiInfo;
    }

}

Ниже приведены зависимости от swagger, которые я использую

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

Ниже приведен файл webconfig конвертера сообщений

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jackson2Converter());
    }

    @Bean
    public MappingJackson2HttpMessageConverter jackson2Converter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(objectMapper());
        return converter;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        return objectMapper;
    }
}

В приведенной ниже ссылке указано, что @EnableWebMvc не должно использоваться в spring -boot webapp, и использование аннотации может вызвать проблемы при вводе swagger-ui. Но, если я не использую аннотацию, веб-приложение не подходит (я вставил трассировку стека ошибок ниже)

http://springfox.github.io/springfox/docs/current/#configuring-the-objectmapper

Трассировка ошибки, когда я не использую @EnableWebMvc Аннотации

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/Users/ngorijala/.m2/repository/io/springfox/springfox-spring-web/2.2.2/springfox-spring-web-2.2.2.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [springfox.documentation.spi.service.RequestHandlerProvider]: : Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/Users/ngorijala/.m2/repository/io/springfox/springfox-spring-web/2.2.2/springfox-spring-web-2.2.2.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.List]: : No qualifying bean of type [org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/Users/ngorijala/.m2/repository/io/springfox/springfox-spring-web/2.2.2/springfox-spring-web-2.2.2.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.List]: : No qualifying bean of type [org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1139)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:799)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:499)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:790)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:337)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1343)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.startWebapp(JettyWebAppContext.java:296)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1336)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:742)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:365)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:163)

У меня такое ощущение, что я пропустил что-то тривиальное. Может кто-то, пожалуйста, взгляните и сообщите мне, чего я не вижу. Спасибо заранее.!!

4b9b3361

Ответ 1

Если вы хотите сохранить аннотацию @EnableWebMvc любым способом, вам нужно добавить следующие

  @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");

            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

Ответ 2

springfox-swagger-ui - это веб- файл, требующий настройки обработчиков ресурсов для информирования сервлета отправки о том, как и какой ресурс обслуживать, когда вы запрашиваете ../swagger-ui.html. Обычно в весенне-загрузочном приложении автоконфигурация заботится о настройке для вас. Причина, по которой он не загружается в вашем случае, заключается в том, что вы дали понять, что приложение будет WebMvcConfigurerAdapter вручную с помощью комбинации WebMvcConfigurerAdapter/@EnableWebMvc.

Вы должны иметь возможность разместить аннотацию @SpringBootApplication в конфигурации основной пружины и полностью избавиться от класса WebConfig.

Так как ваш WebConfig не добавляет никакого значения, кроме того, чтобы убедиться, что JSON имеет отступ, я бы предложил удалить его все вместе и заменить вместо него bean-компонент Jackson2ObjectMapperBuilder.

Для примеров того, как сделать то же самое в spring-mvc/spring-boot и т.д., Взгляните на проект springfox-demos. В частности, взгляните на SpringConfig, чтобы увидеть, как вручную настроить обработчики ресурсов.

Ответ 3

Я сталкивался с этой проблемой раньше, и проблема была в строке ниже в application.properties

spring.resources.add-отображение = ложь

удалите его или измените его значение на истинное

Ответ 4

Это сработало для меня, когда я не переопределил шаблон статического пути.

В весеннем загрузочном приложении просто избегайте " spring.mvc.static-path-pattern " из файла свойств, и swagger-ui будет работать нормально.

Ответ 5

В моем случае я удалил spring.resources.static-locations в файле свойств, и он работает.