본문 바로가기
SpringBoot

[Spring Boot] 06. Swagger 구성하기

by 청양호박이 2019. 11. 11.

스웨거... 흔히 들었던... 그 아이가 아닙니다. Swagger는 Open API Specification (OAS)를 위함 프레임워크 입니다. 이는 Project내 API에 대한 spec의 자동화 관리할 수있는 도구라고 생각하면됩니다. 프로젝트를 진행하다보면, 다른 부서와 협업을 진행하거나, 이미 만들어져 있는 프로젝트에 대해서 유지보수를 진행하게 된다면... 해당 Project내에 어마어마하게 많은 API에 대한 파악이 필요합니다.

 

이런한 spec을 정리하기 위해 API문서화 작업이 필요하며, 이를 직접 한땀한땀 손으로 하게 된다면 많은 공수가 들어가게 됩니다. 게다가 수정이라도 생기게 된다면... 하아 상상만 해도 번거롭지 않을 수 없습니다.

 

이러한 불편함을 줄여주기 위해 나온것이 바로 Swagger라고 생각하시면 됩니다. 그럼 Spring Boot에 Swagger를 적용하는 방법을 알아보겠습니다.

  • POM.xml에 Swagger 관련 dependency 추가
  • Spring 내 Swagger관련 Configuration 추가
  • Controller내 Swagger관련 Annotation 추가
  • Swagger.ui를 통한 확인 

 

1. POM.xml에 Swagger 관련 dependency 추가


앞으로 추가가 필요한 dependency는 아래의 경로에서 검색합니다.

https://mvnrepository.com/

 

Maven Repository: Search/Browse/Explore

Contains the generic annotation processor that is driven by code templates with meta-annotations from japkit-annotations. Last Release on Nov 10, 2019

mvnrepository.com

springfox로 검색하면 가장 높은 순위로... springfox swagger 2 / springfox swagger ui 를 찾을 수 있습니다. 선택해서 들어가 보면... 다음과 같이 최신버전에 대한 사용현황과 update된 날짜를 확인할 수 있습니다.

원하는 버전을 선택하면... 현재 project에 맞는 Maven 코드가 나오게 됩니다. 그렇다면 이 2개를 아래와 같이 POM.xml에 살포시 추가해줍니다.

 

[POM.xml]

		<!-- swagger dependency -->
		<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger2</artifactId>
		    <version>2.9.2</version>
		</dependency>
		<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger-ui</artifactId>
		    <version>2.9.2</version>
		</dependency>

해당 파일을 저장하면, 자동으로 STS에서 다운로드를 수행합니다.

 

 

 

2. Spring 내 Swagger관련 Configuraiton 추가


우선 Annotation을 2개 추가해줍니다. Config이기 때문에... @Configuration 을 추가하고, Swagger를 위한 Annotation인 @EnableSwagger2를 추가합니다.

 

그리고... Controller가 있는 Package인 위치를 지정하고, 기재된 Path를 모두 가져오는 설정을 넣습니다. 

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
	
	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2).select()
				.apis(RequestHandlerSelectors.basePackage("com.example.ayoteralab"))
				.paths(PathSelectors.any())
				.build();
	}

}

더 자세하게 여러가지 설정을 넣을 수 있지만, 이번 단계에서는 이정도로도 충분합니다.

 

 

3. Controller내 Swagger관련 Annotation 추가


 Controller내 추가 가능한 Annotation은 아래의 위치에서 확인이 가능합니다.

https://github.com/swagger-api/swagger-core/wiki/Annotations 

 

swagger-api/swagger-core

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API - swagger-api/swagger-core

github.com

저는 이중에서 @Api / @ApiOperation 만 이번에 사용해 보겠습니다. 이전에 작성한 Controller에 해당 Annotaiton을 추가해 보겠습니다.

2019/11/10 - [SpringBoot] - [Spring Boot] 05. MyBatis Basic Full Test

 

[Spring Boot] 05. MyBatis Basic Full Test

이번에는 앞의 DB Connection Pool과 병행하여, 설정이 잘 되었는지 기본 테스트를 진행해 보겠습니다. 가장 기본적인 API형태의 시작이며, 대부분 이 구조의 확장이나 기능의 추가라고 보시면 됩니다. 우선 이전..

ayoteralab.tistory.com

@RestController
@RequestMapping(value = "/user")
@Api(value = "/user", description = "About user", consumes = "application/json")
public class UserController {
	
	@Autowired
	UserService userService;
	
	@ApiOperation(httpMethod = "GET"
			,value = "User 리스트 조회"
			,notes = "Select User List"
			,response = UserDTO.class
			,responseContainer = "ArrayList")
	@RequestMapping(value = "select", method = RequestMethod.GET)
	public ResponseEntity<ArrayList<UserDTO>> selectUser(){
		return ResponseEntity.ok(userService.selectUser());
	}

}

 

 

4. Swagger.ui를 통한 확인


자동으로 다음의 경로로 API리스트를 확인할 수 있습니다. 

[http://localhost:8080/swagger-ui.html]

 

너무 깔끔하네요. Controller에 기재했던 Path와 DTO까지 확인이 가능합니다. 또한, Path를 클릭해보면 테스트도 가능합니다.

 

지금까지 Swagger에 대해서 알아보았습니다. 

 

-Ayotera Lab-

댓글