본문 바로가기
Spring

[Spring; 스프링] Swagger 설정

by daddydontsleep 2023. 10. 24.
728x90
728x90

Swagger

Spring Boot 프로젝트에서 Swagger를 설정하는 방법은 다음과 같습니다.

1. Maven 또는 Gradle 의존성 추가

Maven:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version> <!-- 현재 사용 가능한 최신 버전으로 업데이트하세요 -->
</dependency>

Gradle:

implementation 'io.springfox:springfox-boot-starter:3.0.0' // 현재 사용 가능한 최신 버전으로 업데이트하세요

2. Swagger 설정 클래스 생성

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("your.package.name")) // 컨트롤러 클래스의 패키지 경로를 지정
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API 문서 제목")
                .description("API 문서에 대한 설명")
                .version("1.0.0")
                .build();
    }
}

3. 컨트롤러 클래스에 API 문서 주석 추가

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Api(tags = "API 컨트롤러") // Swagger 문서에서 그룹화할 태그를 지정
public class MyController {

    @GetMapping("/greet")
    @ApiOperation(value = "인사말 얻기", notes = "간단한 인사말을 얻습니다.")
    public String getGreeting() {
        return "Hello, World!";
    }
}

4. Swagger UI 확인

프로젝트를 실행한 후, 브라우저에서 `http://localhost:포트번호/swagger-ui.html`로 접속하면 Swagger UI를 통해 API문서를 확인할 수 있습니다. 위의 설정에서 `/api/greet` 엔드포인트에 대한 API 문서가 생성됩니다. 필요한 경우 `SwaggerConfig` 클래스와 컨트롤러 메서드의 주석을 수정하여 문서를 자세히 설명할 수 있습니다.

<@EnableSwagger2>

`@EnableSwagger2`는 Spring Boot 프로젝트에서 Swagger를 활성화하는 어노테이션입니다.

이 어노테이션을 사용하면 Swagger UI를 사용하여 API 문서를 생성하고 볼 수 있습니다.

Swagger 2.x 버전에서는 `@EnableSwagger2` 어노테이션을 사용했지만, Swagger 3.x 이상 머전에서는 `@EnableSwagger2` 어노테이션이 더 이상 사용되지 않습니다. Swagger 3.x 이상에서는 `@EnableSwagger2` 대신에 Spring Boot 프로젝트에서는 아래와 같이 `Docket` 빈을 설정하여 Swagger를 활성화 할 수 있습니다.

import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.PathSelectors;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("your.package.name")) // 컨트롤러 클래스의 패키지 경로를 지정
                .paths(PathSelectors.any())
                .build();
    }
}

위의 코드에서 `"your.package.name"`을 실제 프로젝트의 컨트롤러 클래스가 있는 패키지 경로로 변경해야 합니다.

이렇게 하면 Swagger가 해당 패키지 내의 모든 컨트롤러 클래스에서 API 문서를 생성하게 됩니다.

또한, 이 코드는 Swagger 2.x를 사용하는 설정입니다. 최신 버전의 Spring Boot 및 Swagger를 사용한다면, 프로젝트의 의존성과 Swagger 설정을 위한 클래스를 적절히 업데이트하여 사용하시기를 권장합니다.

 

 

 

https://swagger.io/

 

API Documentation & Design Tools for Teams | Swagger

Loved by all • Big & Small Thousands of teams worldwide trust Swagger to deliver better products, faster.

swagger.io

 

728x90
300x250