본문 바로가기
잡다한

SpringBoot에 Swagger3 설정하기(Gradle)

by jisung-kim 2023. 7. 6.

개인적으로 가지고 놀고 있는 토이 프로젝트에 Swagger를 적용하기로 결심했다.

Swagger 같은경우 REST API 명세를 손쉽게 문서화 할 수 있는 라이브러리이다.

대부분의 모든 회사에서 실무에 적용하고 있다.

SpingBoot3.0이상 버전부터는 Swagger3적용되고 Swagger2는 적용되지 않는다.

 

build.gradle

	implementation 'io.springfox:springfox-boot-starter:3.0.0'

 

SwaggerConfig


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;
import springfox.documentation.swagger.web.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.HashSet;
import java.util.Set;

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .consumes(getConsumeContentTypes())
                .produces(getProduceContentTypes())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/api/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Toy API 문서")
                .description("Spring Data Toy Project")
                .version("1.0")
                .build();
    }

    private Set<String> getConsumeContentTypes() {
        Set<String> consumes = new HashSet<>();
        consumes.add("application/json;charset=UTF-8");
        consumes.add("application/x-www-form-urlencoded");
        return consumes;
    }

    private Set<String> getProduceContentTypes() {
        Set<String> produces = new HashSet<>();
        produces.add("application/json;charset=UTF-8");
        return produces;
    }

    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(1)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .validatorUrl(null)
                .build();
    }

}

 

Docket:  Swagger3 설정의 본체  API 정보와, Response,Request Content-Type,  Swagger-Ui에서 보여줄 API 경로. 등 설정

ApiInfo 메소드: API기초 정보 

getConsumeContentTypes, getProduceContentTypes : Reqeust Content-Type, Response Content-Type을 관리

UiConfig: Swagger3의 UI관련 설정

 

SpringSecurity   인증예외처리 

	@Bean
    protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        return  http.cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-resources/**",
                        "/swagger-ui/**",
                        "/v3/api-docs"
                ).permitAll()
                .anyRequest().authenticated()
                .build();
    }

단순히 /swagger-ui/** 만 예외처리하면 안되고 3가지 경로 모두 swagger에서 end-point이기 때문에 예외처리 해줘야한다.

 

http://localhost:포트/swagger-ui/index.html

'잡다한' 카테고리의 다른 글

Docker-Compose mysql 설치  (0) 2023.10.09
H2 인메모리DB 세팅  (0) 2023.07.02