Swagger UI 2 설정하기

By | 2020년 11월 9일
Table of Contents

Swagger UI 2 설정하기

의존성 추가

dependencies {
    implementation 'io.springfox:springfox-swagger-ui:2.9.2'
    implementation 'io.springfox:springfox-swagger2:2.9.2'
}

Swagger 활성화

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/api/**"))
                .build();
    }
}

브라우저에서 http://localhost:8080/swagger-ui.html 를 접속하면 Swagger UI 가 실행된 것을 확인할 수 있습니다.

컨트롤러에 annotation 추가

ApiOperation annotation 을 추가하면 한글 설명을 메소드에 추가할 수 있습니다.

ApiImplicitParams 을 이용해 파라미터에 대한 한글 설명을 추가할 수 있습니다.

@RequiredArgsConstructor
@RestController
public class MenusApiController {

    private final MenusService menusService;

    @ApiOperation(value = "메뉴 저장", notes = "메뉴 아이템을 신규등록합니다.")
    @PostMapping("/v1/settings/menu")
    public ResponseWithDataDto save(@RequestBody MenusSaveRequestDto menusSaveRequestDto) {
        return menusService.save(menusSaveRequestDto);
    }

    @ApiOperation(value = "메뉴 조회", notes = "메뉴 아이템을 조회합니다.")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "메뉴 ID", required = true, dataType = "int", paramType = "path", defaultValue = ""),
    })
    @GetMapping("/v1/settings/menu/{id}")
    public ResponseDto findById(@PathVariable Integer id) {
        return menusService.findById(id);
    }
}

헤더 추가

List<Parameter> 를 이용해 헤더를 추가할 수 있습니다.

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {

        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();

        parameterBuilder
                .name("X-Authorization")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        parameters.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(parameters)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/v1/**"))
                .build();
    }
}

Spring Security

Spring Security 가 활성화 되어 있는 경우, "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs/**" 를 허용해 주어야 합니다.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // ......

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .addFilterBefore(corsFilter(), SessionManagementFilter.class)
                .addFilterBefore(rsaHeaderKeyFilter(), BasicAuthenticationFilter.class)
                .authorizeRequests().antMatchers("/health/**",
                        "/v1/user/**",
                        "/swagger-ui.html",
                        "/webjars/**",
                        "/swagger-resources/**",
                        "/v2/api-docs/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    // ......
}

DTO 에 예제값 표시

@Getter
@NoArgsConstructor
public class MenusSaveRequestDto implements Serializable {

    @ApiModelProperty(example = "0")
    private Integer pidx;
    @ApiModelProperty(example = "테스트 메뉴")
    private String menuName;
    @ApiModelProperty(example = "Y")
    private String useyn;
}

답글 남기기