본문 바로가기

Spring/서브 프로젝트

Springdoc 라이브러리를 통한 Swagger 적용

728x90
[ 환경 ]
IDE : Intellij
FrameWork : Spring Boot 3.2.3
Language : Java17

 

1. build.gradle에 라이브러리 추가

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

 

2. application.yml 수정

springdoc:
  api-docs:
    path: /api-docs
    groups:
      enabled: true
  swagger-ui:
    path: /swagger
    enabled: true
    groups-order: asc
    tags-sorter: alpha
    operations-sorter: alpha
    display-request-duration: true
    doc-expansion: none
  cache:
    disabled: true
  model-and-view-allowed: true

 

3. 화면 확인 : 127.0.0.1:자신의 포트주소

 

4. 3번 화면에서의 title, version, description 변경

[[ SwaggerConfig.java ]]

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("test-swagger-title")
                        .version("1.0")
                        .description("test-swagger"));
    }

    @Bean
    public GroupedOpenApi api() {
        String[] paths = {"/api/**"};
        String[] packagesToScan = {"com.example.demo.test"};
        return GroupedOpenApi.builder().group("api-test")
                .pathsToMatch(paths)
                .packagesToScan(packagesToScan)
                .build();
    }
}

 

5. Swagger 목록에 나올 api 생성

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Tag(name = "api 테스트", description = "Swagger 테스트용 API")
public class TestController {

    @GetMapping("/test")
    @Operation(summary = "test", description = "test")
    public String Hello() {
        return "hello";
    }
}

 

6. 결과 확인

 

7. api 확인