Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

그라가승훈

[SpringBoot] - Swagger 적용 본문

Spring

[SpringBoot] - Swagger 적용

그라가승훈 2023. 10. 22. 21:42

- Swagger 란?

간단한 설정만으로 API 목록을 웹에서 확인 및 테스트 할 수 있게 해주는 라이브러리.

 

1. gradle 에 라이브러리 추가

 

현재 가장 많이 사용하는 2.9.2 를 사용했다.

// swagger
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'

2. application.properties 에 설정 추가

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

SpringBoot 2.6 버전 이후에 spring.mvc.pathmatch.matching-strategy 값이 ant_apth_matcher에서 path_pattern_parser로 변경되면서 몇몇 라이브러리에서 오류가 있다고 한다.

값을 ant_apth_matcher 로 설정.

3. SwaggerConfiguration 생성

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                // 1
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                // 2
                .paths(PathSelectors.any())
                .build();
    }
}

1. com.example 패키지 내에 RequestMapping으로 설정된 모든 URL 을 선택.

2. PathSelectors.any("/api/**") 와 같이 사용하면 특정 URI 를 가진 주소만 선택 가능.

4. Swagger 설명 추가

swagger 어노테이션을 사용해서 설명을 추가할 수 있다.

  • @Api : 컨트롤러에 대한 설명.
    • ex) @Api(tags = "게시판 REST API")
      컨트롤러의 이름을 설정
  • @ApiOperation : API 에 대한 설명.
    • ex) @ApiOperation(value = "게시글 목록 조회", notes = "게시글 목록을 조회합니다.")
      API에 대한 이름과 설명을 설정
  • @ApiModel : DTO 같은 모델에 대한 설명
    • ex) @ApiModel(value = "BoardDto : 게시글 내용", description = "게시글 내용")
      모델에 대한 이름과 설명을 설정
  • @ApiModelProperty: 모델에 대한 요소 설명
    • ex) @ApiModelProperty(value = "게시글 번호")
      모델에 대한 이름을 설정

5. Swagger 확인

swager URL : http://localhost:8080/swagger-ui.html

위 주소로 들어가서 확인.

 

Comments