spring
SpringBoot 프로젝트에 Swagger 적용 및 오류 해결
haroutine
2023. 1. 31. 22:18
Swagger란?
Swagger는 SpringBoot 프로젝트를 기반으로 자동으로 api 문서를 만들어준다
Swagger를 적용시키려면 먼저 build.gradle에 의존성을 추가해준다
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
그런다음 Swagger Config 파일을 작성한다
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String API_NAME = "API 이름";
private static final String API_VERSION = "버전";
private static final String API_DESCRIPTION = "API 명세서 설명";
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(API_NAME)
.version(API_VERSION)
.description(API_DESCRIPTION)
.contact(new Contact("이름", "url", "email"))
.build();
}
}
Docket은 문서를 작성할 때 속성을 사용자가 변경할 수 있다.
apiInfo() : api 메타 정보를 설정할 수 있다
ex) API 문서명 , 문서 버전, API 문서 설명, 연락처 정보 등을 설정할 수 있다
@Api(tags = {"Item CRUD 관련한 Controller"})
@RequestMapping("/items")
@RestController
public class ItemController {
private ItemService itemService;
public ItemController(ItemService itemService){
this.itemService = itemService;
}
@ApiOperation(value = "상품 정보 저장", notes = "판매자는 상품 정보를 등록할 수 있다")
@PostMapping("/new")
public ResponseEntity<?> addItem(@RequestBody Item item){
Item item = itemService.createItem(item);
return ResponseEntity.ok().body(item);
}
@GetMapping("/{id}")
@ApiImplicitParam(name = "id", value = "상품 아이디", dataType = "Long")
public ResponseEntity<?> getItems(@PathVariable("id") Long itemId){
Item item = itemService.findOne(itemId);
return ResponseEntity.ok().body(item);
}
}
@ApiOperation 은 메소드를 설명을 작성할 수 있다
- value : 메소드의 역할 설명
- note : 메소드의 상세 설명 작성
@ApiImplicitParam 은 API 호출에 필요한 파라미터들의 설명을 작성할 수 있다
- name은 파라미터명
- value는 파라미터 설명
- datatype은 파라미터 데이터 타입
Swagger를 적용시킨 후 어플리케이션을 실행하니 아래와 같은 오류가 발생하였다
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
SpringBoot 2.6버전 이후에 spring.mvc.pathmatch.matching-strategy 값이
ant_path_matcher에서 path_pattern_parser로 변경되면서 오류가 발생하였다
이 때, application.yml 이나 application.properties 파일에서 아래 코드를 추가하니 오류가 해결되었다
application.yml
mvc:
pathmatch:
matching-strategy: ant_path_matcher
application.properties
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
반응형