spring

[Spring Boot] 스피링 부트 3.x Swagger Ui 설정

박진만 2023. 3. 21. 18:06
반응형

- Spring Boot 3.0.4, springdoc 2.0.4 기준
- swagger : springfox, springdoc 2가지 라이브러리가 있음.
  springfox 는 최근 업데이트가 없고 Spring Boot 3점 대 적용 시 일부 오류 발생 -> java 17 적용 때문인 것 같음 (Spring Boot 3 버전은 java 17 이상 필수)
  그래서 springdoc 적용

1. build.gradle
- implementation 추가
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
implementation 'org.springframework.boot:spring-boot-starter-validation'

2. application.properties
- springdoc 설정 내용 추가
#springdoc
springdoc.version=v1.0.0
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.swagger-ui.groups-order=DESC
springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.display-request-duration=true

springdoc.api-docs.path=/api-docs
springdoc.show-actuator=true
springdoc.default-consumes-media-type=application/json
springdoc.default-produces-media-type=application/json
springdoc.paths-to-match=/**

3. SwaggerConfig.java
- swagger API 설정 : 기본 정보 설정 및 JWT 설정

import java.util.Arrays;

import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;

@Configuration
public class SwaggerConfig {

    @Bean
    public GroupedOpenApi manmanApi() {
        return GroupedOpenApi.builder()
            .group("manman Service API v1")
            .pathsToMatch("/**")
            .build();
    }
    
    @Bean
    public OpenAPI manmanOpenAPI(@Value("${springdoc.version}") String springdocVersion) {
    	
    	Info info = new Info().title("manman Service API 명세서")
            .description("manman 프로젝트 서비스 API 명세서입니다.")
            .version(springdocVersion);
                
    	SecurityScheme securityScheme = new SecurityScheme()
            .type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")
            .in(SecurityScheme.In.HEADER).name("Authorization");

	SecurityRequirement schemaRequirement = new SecurityRequirement().addList("bearerAuth");
    	
        return new OpenAPI()
            .components(new Components().addSecuritySchemes("bearerAuth", securityScheme))
            .security(Arrays.asList(schemaRequirement))
            .info(info);
        
    }
    
}

4. MusicController.java
- Controller 설정 : 설정한 정보가 swagger-ui.html 화면에 표현된다.

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.manman.common.response.ErrorResponse;
import com.manman.music.service.MusicService;
import com.manman.music.vo.MusicRequest;
import com.manman.music.vo.MusicResponse;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "Music", description = "Music api 입니다.")
@RestController
@RequestMapping("/music")
public class MusicController {
	
	final private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MusicService musicService;
	
	@Operation(summary = "Music 리스트 조회", description = "Music 리스트 정보가 조회됩니다.")
	@ApiResponses({
		@ApiResponse(responseCode = "200", description = "OK",
			content = @Content(schema = @Schema(implementation = MusicResponse.class))),
		@ApiResponse(responseCode = "400", description = "BAD REQUEST", 
			content = @Content(schema = @Schema(implementation = ErrorResponse.class))),
		@ApiResponse(responseCode = "404", description = "NOT FOUND",
			content = @Content(schema = @Schema(implementation = ErrorResponse.class))),
		@ApiResponse(responseCode = "500", description = "INTERNAL SERVER ERROR",
			content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
	})
	@Parameters({
		@Parameter(name = "category", description = "카테고리", example = "R01", required = true),
		@Parameter(name = "regYmd", description = "등록일시", example = "20230305", required = false)
	})
	@RequestMapping(value = "/selectMusicList", method = {RequestMethod.POST, RequestMethod.GET})
	ResponseEntity<List<MusicResponse>> selectMusicList(
		@Parameter(hidden = true) @Validated(MusicRequest.validSelectMusicList.class) @RequestBody MusicRequest musicRequest
	) throws Exception {

		logger.debug("MusicController selectMusicList musicRequest.getCategory() : " + musicRequest.getCategory());
		logger.debug("MusicController selectMusicList musicRequest.getRegYmd() : " + musicRequest.getRegYmd());

		return ResponseEntity.ok().body(musicService.selectMusicList(musicRequest));

	}
    
}

5. MusicRequest.java
- 요청 값 관리 Class : 요청 항목 정의 및 각 항목 별 validation 을 정의한다.

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MusicRequest {
	
    public interface validSelectMusicList {}

    @NotBlank(groups = validSelectMusicList.class)
    @Schema(description = "카테고리")
    private String category;

    @Schema(description = "등록일시")
    private String regYmd;

    @Schema(description = "가수")
    private String artist;    

    @Schema(description = "제목")
    private String title;    

    @Schema(description = "등록번호")
    private String regNo;    

    @Schema(description = "비디오 ID")
    private String videoId;    

    @Schema(description = "썸네일")
    private String thumbnail;

}

6. MusicResponse.java
-  응답 값 관리 Class : 응답 항목을 정의한다.

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class MusicResponse {
	
    @Schema(description = "등록번호")
    private String regNo;

    @Schema(description = "순위")
    private int rank;

    @Schema(description = "제목")
    private String title;

    @Schema(description = "가수")
    private String artist;

    @Schema(description = "등록일시")
    private String regYmd;

    @Schema(description = "카테고리")
    private String category;

    @Schema(description = "썸네일")
    private String thumbnail;

    @Schema(description = "비디오 ID")
    private String videoId;
	
}

7. swagger-ui 화면

반응형