Web

Swagger

잔망루피 2023. 1. 14. 01:59

내가 사용한 Spring Boot 버전은 2.6.14

 

Swagger를 적용 후 /swagger-ui로 접속

나는 포트번호를 8011로 설정했었다.

 

 

🐸 Swagger 사용하기

 

1. build.gradle에 추가

implementation 'io.springfox:springfox-swagger-ui:3.0.0'
implementation 'io.springfox:springfox-swagger2:3.0.0'
implementation 'io.springfox:springfox-boot-starter:3.0.0'

 

 

2. Swagger 사용을 위해 configuration 작성

@Configuration
@EnableSwagger2
public class SpringFoxConfig {
    private static final String API_NAME = "User-server API";
    private static final String API_VERSION = "0.0.1";
    private static final String API_DESCRIPTION = "User-server API 명세서입니다.";

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(컨트롤러 패키지명 작성))	
                .paths(PathSelectors.any())
                .build();
    }

    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(API_NAME)
                .version(API_VERSION)
                .description(API_DESCRIPTION)
                .build();
    }

    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
                                                                         ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier,
                                                                         EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties,
                                                                         WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment,
                basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
                corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
                shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment,
                                               String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
                || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }
}
@EnableSwagger2 Swagger 지원을 사용하도록 설정해야 한다는 것을 나타낸다.
@Configuration을 달고 있는 Spring java config에 적용되어야 한다.
SpringSwaggerConfig에 정의된 모든 필요한 빈을 로드한다.

👇 .apis(RequestHandlerSelectors.basePackage(컨트롤러 패키지명 작성))는 아래가 예시다.

.apis(RequestHandlerSelectors.basePackage("com.example.userserver.controller"))

 

 

3. 에러 해결

`org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null`

`Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null`

Spring Boot 2.6 이후로는 이 에러가 뜰거다.

Spring Boot 2.6 Release Note를 보니 default였던 AntPathMatcher가 PathPatternParser로 바꼈다.

아래 2가지를 적용해서 해결한다.

  1. webEndpointServletHandlerMapping 빈을 등록(2번에 SpringFoxConfig 소스 코드 참고)
  2. application.yml에 아래를 추가
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

application.properties면 

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

 

 

Swagger URI 변경

springfox.documentation.swagger.v2.path=/api
springfox.documentation.swagger-ui.base-url=/api

application.properties에 지정해주면 localhost:8080/api/swagger-ui/index.html로 접속할 수 있다.

 

 


참고 👇

https://velog.io/@bora_u/Swagger-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0

 

[빵빵] Swagger 적용하기

안녕하세요! 오늘의 포스팅 주제는 Swagger입니다! Spring boot를 이용하여 REST API를 개발하는 사람이라면, API 명세서를 작성해본 경험이 있을 것입니다. API 명세서는 해당 API에 대한 정보를 정리한

velog.io

 

https://stackoverflow.com/questions/72235752/cannot-invoke-org-springframework-web-servlet-mvc-condition-patternsrequestcond

 

Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is

I'm trying to run Springdoc with Spring Boot 2.6.7. Configuration: @Configuration public class SwaggerConfiguration { @Bean public GroupedOpenApi publicApi() { return GroupedOpenApi.buil...

stackoverflow.com

 

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes

 

GitHub - spring-projects/spring-boot: Spring Boot

Spring Boot. Contribute to spring-projects/spring-boot development by creating an account on GitHub.

github.com

 

반응형

'Web' 카테고리의 다른 글

JWT 인증  (0) 2023.03.09
Preflight request  (0) 2023.02.05
nGrinder 설치  (0) 2023.01.03
JWT  (0) 2022.12.09
CORS  (0) 2022.10.07