Попытка связаться с swagger-ui или api / api-docs, но выдает ошибку 404 - PullRequest
1 голос
/ 06 июля 2019

Это мой первый пост, поэтому не стесняйтесь оставлять отзывы или если я что-то не так делаю :)

Я использую весеннюю загрузку и рестайзи:

<!-- Spring Boot -->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-dependencies</artifactId>
 <version>2.1.0.RELEASE</version>
 <type>pom</type>
 <scope>import</scope>
</dependency>
<dependency>
  <groupId>com.paypal.springboot</groupId>
  <artifactId>resteasy-spring-boot-starter</artifactId>
  <version>2.3.4-RELEASE</version>
</dependency>

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

<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>

Эти зависимости загружены в мой репозиторий, все выглядит хорошо.


Я добавил этот класс, чтобы сделать самый простой класс конфигурации:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

Когда я запускаю приложение в отладочном моде, я вхожу в этот предыдущий Бин. Evrything выглядит хорошо.


Когда я запускаю приложение Spring:

@SpringBootApplication
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class,RabbitAutoConfiguration.class})
public class SituationServicesApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(SituationServicesApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
    }
}

Все выглядит хорошо:

2019-07-06 15:43:27.222  INFO 6336 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]

Но когда я пытаюсь добраться до swagger-ui.html:

http://localhost:8092/test/v2/api-docs

или

http://localhost:8092/test/swagger-ui.html

У меня ошибка 404:

"RESTEASY003210: Не удалось найти ресурс для полного пути: http://localhost:8092/test/v2/api-docs".

Я попытался изменить URL-адрес по умолчанию, добавив свойство: springfox.documentation.swagger.v2.path=v2/api-docs-test

Это кадры 404.

Я пробовал с нуля новый пустой проект, и он работал просто отлично. Я думаю, что-то не так с моим проектом.

Я уверен в используемом URL.

Вы знаете, как я могу отладить эту проблему? Могу ли я увидеть какой-то созданный источник из Swagger? Могу ли я поставить на него какой-нибудь журнал, чтобы узнать, откуда возникла проблема?

Ответы [ 2 ]

0 голосов
/ 06 июля 2019

@ Пьеро, не могли бы вы проверить правильность контекста и порта, настроенных в приложении, и адреса, используемого в URL для проверки пользовательского интерфейса Swagger?Как вы упомянули, когда вы создавали новый проект с нуля, он работал нормально, проблема может быть связана с context-path / port.

0 голосов
/ 06 июля 2019

Если вы используете Spring Security, вам нужно добавить еще несколько настроек, как показано ниже.

Полный рабочий пример

SecurityConfig.java

package com.swagger.demo.security;


import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{

    //Swagger Resources
        @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/");
        }

    //If you are using Spring Security Add Below Configuration

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
            .antMatchers(HttpMethod.OPTIONS,"/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{

         http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers("/**", "/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
         .permitAll()
         .anyRequest().authenticated(); 
    }

}

SwaggerConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
   @Bean
   public Docket apiDocket() {

       Docket docket =  new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swagger.demo"))
                .paths(PathSelectors.any())
                .build();

       return docket;

    } 
}

pom.xml

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

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-core</artifactId>
            <version>2.9.2</version>
        </dependency>

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