개발일지/SPRING

[Spring] Spring Boot 3.x에 Swagger 설정하기 (예시 코드)

양쏘쏘 2024. 6. 11. 13:39
728x90
반응형

Spring swagger

API 테스트를 위해서 Postman을 쓸 수도 있지만 좀 더 쉽게 하기 위해 Swagger를 세팅할 수도 있습니다. 

 

1. 라이브러리 사용을 위해 dependencies에 추가

//gradle
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'	//swagger
//maven
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.5.0</version>
   </dependency>

 

2. Config 파일 추가

package com.tutorial.spring.global.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI openAPI(){
        return new OpenAPI()
                .info(new Info()
                        .title("API")
                        .description("API의 Docs와 테스트을 제공합니다.")
                        .version("1.0.0"));
    }
}

 

이 두 개만 설정하면 끝납니다. 아래의 기본 경로로 들어가면 Swagger가 잘 뜹니다.

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

 

경로는 Application.properties에서 아래처럼 커스텀해줄 수도 있습니다. 

springdoc.swagger-ui.path=/swagger-ui.html

 

 

[학습 출처]

 

OpenAPI 3 Library for spring-boot

Library for OpenAPI 3 with spring boot projects. Is based on swagger-ui, to display the OpenAPI description.Generates automatically the OpenAPI file.

springdoc.org

 

728x90