개발
[Swagger] 스프링부트 3.0.6 + Swagger(springdoc) 적용
BiniForBini
2023. 7. 26. 17:43
build.gradle 파일
/*swagger*/ implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' implementation 'org.hibernate:hibernate-validator:8.0.0.Final'
hibernate-validator를 추가하지 않으면 에러가 발생한다.
→ Unable to create a Configuration, because no Jakarta Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
yml 파일
springdoc: packages-to-scan: com.example.gg default-consumes-media-type: application/json;charset=UTF-8 default-produces-media-type: application/json;charset=UTF-8 swagger-ui: path: /api-docs # Swagger UI 경로 tags-sorter: alpha # alpha: 알파벳 순 태그 정렬, method: HTTP Method 순 정렬 operations-sorter: method # alpha: 알파벳 순 태그 정렬, method: HTTP Method 순 정렬 api-docs: path: /api-docs show-actuator: true
SecurityConfig
.authorizeRequests() .requestMatchers("/register", "/login", "/refresh", "/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**").permitAll() .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/user/**").hasRole("USER") .anyRequest().denyAll()
swagger와 관련된 url을 permitAll 해준다.
에러발생 ㅠ_ㅠ 확인해보니 링크가 "v3/api-docs/**"가 아니라 "/api-docs/**"로 돼있어서 SecurityConfig에서 해당 주소를 permitAll해주니 정상적으로 작동했다. 이 사진에서는 yml의 설정이 적용되지않은 상태다.
SwaggerConfig
import io.swagger.v3.oas.models.Components; 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(){ Info info = new Info() .title("Lolonoa 프로젝트") .version("v0.0.1") .description("목표: 3달 안에 Lolonoa 프로젝트 완성시키기 2023.07.24~"); return new OpenAPI() .components(new Components()) .info(info); } }
편리한 사용을 위한 수정
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI openAPI1(){
Info info = new Info()
.title("Lolonoa 프로젝트")
.version("v3")
.description("목표: 3달 안에 Lolonoa 프로젝트 완성시키기 2023.07.24~");
return new OpenAPI()
.components(new Components())
.info(info);
}
@Bean
public GroupedOpenApi group1(){
return GroupedOpenApi.builder()
.group("유저")
.pathsToMatch("/user/**")
.build();
}
}
GroupedOpenApi를 사용해 경로마다 그룹화해준다.
@Operation(summary = "로그인", description = "로그인 메서드입니다.")
// @ApiResponses(value = {
// @ApiResponse(responseCode = "200", description = "로그인 성공", content = @Content(schema = @Schema(implementation = Member.class))),
// @ApiResponse(responseCode = "401", description = "Bad Request", content = @Content(schema = @Schema(implementation = Error.class))),
//
// })
@PostMapping(value = "/login")
public ResponseEntity<SignResponse> login(@RequestBody LoginRequest request) throws Exception {
return new ResponseEntity<>(memberService.login(request), HttpStatus.OK);
}
@Operation 애노테이션을 붙여 swagger에서 보기 편하게 변경했다. 개발을하다 추가적으로 필요하다면 @ApiResponses로 세부사항을 기재하면 된다.
