[Swagger] Spring Boot에 Swagger 3.0 적용하기
- Java : 1.8
- Spring Boot : 2.3.0
- pom.xml
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- Swagger 2와 3이 큰 차이가 없다고 해서 3.0을 사용하기로 했다.
- swagger관련 dependency를 추가해주고, 프로젝트 우클릭-maven update
*mvn Repository 에서 가져옴 : https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter/3.0.0
SwaggerConfig
package com.acorn.project.swagger.config;
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)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.acorn.project.springswagger.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Practice Swagger")
.description("practice swagger config")
.version("1.0")
.build();
}
}
- Config 파일 작성
HelloController
package com.acorn.project.springswagger.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
@RestController
public class HelloController {
@Operation(summary = "test hello", description = "hello api example")
@ApiResponses ({
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "400", description = "BAD REQUEST"),
@ApiResponse(responseCode = "404", description = "NOT FOUND"),
@ApiResponse(responseCode = "500", description = "INTERNAL SERVER ERROR")
})
@GetMapping("/hello")
public ResponseEntity<String> hello(@Parameter(description = "이름", required = true) @RequestParam String name) {
return ResponseEntity.ok("hello " + name);
}
}
http://localhost:9000/project/swagger-ui/index.html
(IP 및 포트번호/기본경로/swagger-ui/index.html)
- 컨트롤러 작성 후 위 경로로 요청하면 Swagger UI 화면이 출력된다.
* Swagger 관련 참고한 블로그: https://bcp0109.tistory.com/326
* https://goyunji.tistory.com/137
- 만약 프로젝트를 run할 때 'documentationPluginsBootstrapper' 에서 bean을 생성할 수 없다는 오류가 나오면 위 블로그 참고!