codememo

Springfox Swagger-UI가 추가되었지만 작동하지 않습니다. 제가 놓치고 있는 것은 무엇입니까?

tipmemo 2023. 2. 12. 17:55
반응형

Springfox Swagger-UI가 추가되었지만 작동하지 않습니다. 제가 놓치고 있는 것은 무엇입니까?

다음의 순서에 따릅니다.

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

프로젝트에 다음과 같은 종속성을 추가했습니다.

compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"

Spring Fox Swagger를 다음과 같이 설정했습니다.

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 api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

Swagger UI가 활성화되지 않은 것 같습니다.나는 시도했다.

내가 얻는 건

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

로그에는 다음과 같이 표시됩니다.

2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

http://localhost:8080/http-local-host가 반환됩니다.

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

제가 무엇을 빠뜨리고 있나요?

Springfox 3.0.0은 Spring Boot <= 2.6.0-M2에서만 작동하며 그 이상의 버전에서는 작동하지 않습니다.

2.6 M2 < > 2.6 M2 < >
spring1.spring.mvc.pathmatch.spring-mvc=ANT_PATH_MATCHER #-> App.properties
가 없으면 - actuator, 추 - - - - -
WebMvc 2. @Enable WebMvc
3. io. springfox > = 3과 같은 단계로 마이그레이션합니다.x

io. springfox > = 2.X

io. springfox > = 3.x

<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>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
URL " " " URL
http://localhost:8080/http-ui.syslog
URL " " " URL
http://localhost:8080/http-ui/
http://localhost:8080/http-ui/index.displays
★★★

mvn clean

★★★

mvn clean

@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2

나는 이 대답들을 대부분 시도해봤지만, 최종 해결책은 슬금슬금 다가오고 있었다.

올바른 URL은 다음과 같습니다.

http://localhost:8080/http-ui/

Springfox swagger-ui 3.x.x 를 사용하고 있습니다.

완전한 스웨거 설정에 대해서는http://http://muralitechblog.com/swagger-rest-api-dcoumentation-for-spring-boot/ 를 참조해 주세요.

이미 많은 답변들이 정답을 언급했지만, 여전히 오류에 대한 혼란이 있었다.

Spring Boot 버전 > = 2.2를 사용하는 경우 SpringFox Swagger 버전 3.0.0을 사용하는 것이 좋습니다.

이제 pom.xml에 추가할 필요가 있는 의존관계는 1개뿐입니다.

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

응용 프로그램이 시작되면 새 스웨거 URL하나를 누르면 문서를 얻을있습니다.

옵션 1: http://localhost: 8080/swagger-ui/

옵션 2: http://localhost: 8080/swagger-ui/index.html

경로 변수가 /{var}인 요청 매핑을 가진 엔드포인트가 있었기 때문에 이 문제가 발생했습니다.이는 GET 엔드포인트와 POST 엔드포인트(예: GET / {var} 및 POST / {var} block swagger-ui) 모두에 문제가 있는 것으로 나타났습니다.내가 길을 좀 더 구체적으로 만들자, 나는 스웨거-의 일을 하게 되었다.

https://github.com/springfox/springfox/issues/1672에서 인용

스프링이 하나의 변수 스웨거로 단순한 경로를 찾을 때 URL을 가로채지 못합니다.

다양한 아이디어를 댓글로 조사하여 발견.

Spring Version > = 2.2의 경우 종속성 springfox-boot-disples를 추가해야 합니다.

pom.xml:

<properties>
    <java.version>1.8</java.version>
    <io.springfox.version>3.0.0</io.springfox.version>
</properties>

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
</dependencies>

Application Swagger Config

@Configuration
@EnableSwagger2
public class ApplicationSwaggerConfig {

    @Bean
    public Docket employeeApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

}

Swagger-UI 링크: http://localhost:8080/swagger-ui/index.html#/

버전 3.0.0의 경우 종속성은 1개뿐입니다.

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

그런 다음 swag-ui에 액세스할 수 있습니다.

  • http://localhost:8080/swagger-ui/#
  • http://localhost:8080/swagger-ui/index.html

버전 2.x.x의 경우

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

에 접속합니다.http://localhost:8080/swagger-ui

Spring Boot 버전 > = 2.2를 사용하는 경우 SpringFox Swagger 버전 3.0.0을 사용하는 것이 좋습니다.pom.xml 의존관계 설정은 다음과 같이 유지합니다.

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

다음과 같이 Swagger 구성 클래스를 유지합니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

public static final Contact DEFAULT_CONTACT = new Contact(
        "Sample App", "http://www.sample.com", "sample@gmail.com");

public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(
        "Awesome API Title", "Awesome API Description", "1.0",
        "urn:tos", DEFAULT_CONTACT,
        "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", Arrays.asList());

private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =
        new HashSet<String>(Arrays.asList("application/json",
                "application/xml"));

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(DEFAULT_API_INFO)
            .produces(DEFAULT_PRODUCES_AND_CONSUMES)
            .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
 }
}

이제 http://localhost:8080/swagger-ui/index.html#/로 이동하여 스웨거 UI에 액세스합니다.

또, 패스 매핑이 없는 컨트롤러(「/」에의 매핑)가 있는 것도 문제였습니다.스웨거의 자원에 대한 요청을 차단한 겁니다

스웨거를 @Configuration@EnableWebMvc1개의 파일로 분류합니다.

동작하지 않음:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

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

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/");

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

솔루션은 문서와 같이 2개의 자바 클래스로 구분하는 것이었습니다.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

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


@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {

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

}

나도 최근에 비슷한 문제가 있었다.

http://localhost:8080/http-ui/ - 동작하지 않음

http://localhost:8080/http-ui/index.http:정상작동

...결국 이 문제는 내 pom.xml이 엉망인 것이 원인이었다.

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

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

처음 두 개의 종속성을 삭제했기 때문에 springfox-boot-starter만 남아서 maven을 몇 번 청소하고 앱을 재시작한 후 첫 번째 경로도 정상적으로 동작하기 시작했습니다.http://localhost:8080/swagger-ui/

io. springfox > = 3 및 Spring Security 사용

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

Spring Fox Config 클래스

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

private ApiInfo getApiInfo() {
    return new ApiInfo(
            "company_name",
            "message here",
            "VERSION_1",
            "TERMS OF SERVICE URL",
            new Contact("company", "url", "EMAIL"),
            "LICENSE",
            "LICENSE URL",
            Collections.emptyList()
      );
     }
   }

WebConfig 클래스(@EnableWebMvc 주석이 사용되지 않았는지 확인하십시오.그렇지 않으면 오류가 발생합니다)

   @Configuration
  //@EnableWebMvc
   public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", 
           "OPTIONS");
        }
      }

Security Configuration 클래스

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
        // -- Swagger UI v2
        "/v2/api-docs",
        "/swagger-resources",
        "/swagger-resources/**",
        "/configuration/ui",
        "/configuration/**",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        // -- Swagger UI v3 (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui/",
        "/swagger-ui"
        // other public endpoints of your API may be appended to this array

        @Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
    httpSecurity.cors();
    httpSecurity.csrf().disable();
    httpSecurity.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .anyRequest()
                .authenticated();

                httpSecurity.addFilterBefore(jwtRequestFilter, 
                             UsernamePasswordAuthenticationFilter.class);
         }
     };

" " " @RequestMapping("/")레벨에서 ('이후'로)@RestController\@Controller더 이상 하지 않을 수 .Request method 'GET' not supportedDhermanns가 제안해준 덕분에

@RequestMapping("/")이치노

저장소 maven 아래에 항아리 파일이 없습니다.${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2아래 단계를 거치면 모든 것이 정상입니다.

이 문제는 다음 순서로 해결했습니다.

  • ${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2
  • 2.9.2의 파일이 완료되었는지 확인합니다.파일이 없는 경우는, 2.9.2 디렉토리 전체를 삭제합니다.
  • 실행하다reimport all maven projects인텔리사상으로

스프링 부트 버전은 2.2.2입니다.

swagger-ui.html 요청 메서드 'get' not supported\request 메서드 'get'이 지원되지 않습니다.\supported 메서드 투고

나는 문제를 해결할 수 있었다.

컨트롤러 api @RequestMapping()에 경로 정보가 없습니다. 아래 Fix - @RequestMapping(값 = '/v1/createAnalytic')과 같은 경로가 제공되었습니다.

버전 - V3 || io. springfox > = 3.0.0을 사용하는 경우

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

자바 코드

@Configuration
@EnableSwagger2

public class SwaggerConfig {

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors.basePackage("Your Controller package name"))
            .paths(PathSelectors.any()).build();
}

}

V3 브라우저 URL ->http://localhost:8080/swagger-ui/#/ 실행(필수 필요): Mvn 클린

IDE 를 재기동해 주세요.

이러한 제안들을 많이 시도해 보았지만, 아직 아무런 운이 따르지 않은 후, 저는 이 블로그 포스트를 발견했습니다.https://medium.com/swlh/openapi-swagger-ui-codegen-with-spring-boot-1afb1c0a570e

여기서 저자는 다음과 같이 말했다.Whitelabel Error Page가 표시되면 IDE를 재시작하고 프로젝트를 다시 실행하십시오."

이건 마법처럼 작동했어.

이 댓글로 많은 시간을 절약할 수 있었습니다.즉, 프로젝트의 누군가가 컨트롤러에 다음과 같은 매핑을 추가한 것을 알 수 있었습니다.

@RestController("/api/test")

물론 이렇게 생겼을 겁니다.

@RestController
@RequestMapping("/api/test")

위와 같은 이유로 swag-ui를 보려다 405개의 답변을 받았습니다.

@RestController의 문서는 이 문제를 보다 정확하게 설명합니다.

이 값은 자동 검출된 컴포넌트의 경우 스프링빈으로 변환되는 논리 컴포넌트 이름을 제안할 수 있습니다.반환: 권장 컴포넌트 이름(있는 경우)을 반환한다(그렇지 않은 경우 문자열을 비워둔 경우). 이후: 4.0.1

버전 3.0을 사용하려면 매뉴얼도 변경해야 합니다.Docket Constructor에서 OAS_30을 입력합니다.

@Bean
public Docket api() {
  return new Docket(DocumentationType.OAS_30)
                           .select()
                           .apis(RequestHandlerSelectors.any())
                           .paths(PathSelectors.any())
                           .build();
}

저는 기존 API 때문에 문제가 되었습니다.

나는 한 잔이 있었어요Existing API같은 컨트롤러에서

http://localhost:8080/{PathParam}

로 바꿨습니다.

http://localhost:8080/domain/{PathParam}

문제가 해결되었습니다!!!

저는 단순히 제 maven을 새로고침 했을 이고, 제 POM 파일에는 다음과 같은 의존관계가 있습니다. ' 4.0.0 org. springframework.boot spring-boot-starter-parent 2.7.4 com.example demo 0.0.1-SNAPSHOT 데모 프로젝트 for Spring Boot <java.version> 1.8 </module.version>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>


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


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
`

이를 수정하려면 두 가지 작업을 수행해야 했습니다.

  1. 아래의 의존관계를 추가하고 다른 스웨거 의존관계를 제거했다.

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    
  2. org. springframework.pom.xml의 보안 의존성이 swagger-ui를 차단하고 있었기 때문에 swagger UI의 보안을 우회하기 위해 아래 코드를 추가했습니다.

     @Configuration
     public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
         @Override
         public void configure(WebSecurity web) throws Exception {
             web.ignoring().antMatchers("/v2/api-docs",
                                        "/swagger-resources/**",
                                        "/swagger-ui/**");
         }
     }
    

언급URL : https://stackoverflow.com/questions/46151540/added-springfox-swagger-ui-and-its-not-working-what-am-i-missing

반응형