서버로 요청되는 URL 리스트를 HTML 화면으로 문서화, 테스트 할 수 있는 라이브러리.
1. pom.xml
...
<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>
...
2. SwaggerConfig.java
.apiInfo는 Swagger API문서에 대한 설명을 표기하는 메소드.
.apis는 Swagger API 문서로 만들기 원하는 basePackage 경로.
.paths는 url 경로를 지정하여 해당 url에 해당하는 요청만 Swqgger API문서로 만든다.
package kr.co.zikapi.common.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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Demo").description("API EXAMPLE").build();
}
@Bean
public Docket commonApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("example").apiInfo(this.apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("kr.co.zikapi")).paths(PathSelectors.ant("/api/**")).build();
}
}
3. SampleController.java
@ApiOperation : 메서드 설정 및 설명문을 기입
SwaggerConfig에서 해당 Controller를 Swagger API문서로 지정
@RestController
@RequestMapping("/api")
public class SampleController {
private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
@Autowired
private Environment environment;
@Autowired
private SampleService sampleService;
/**
* 샘플
*
* @param request
* @param response
* @return
*/
@GetMapping("getSample")
@ApiOperation(value = "Test Sample", tags = "sample")
public String getSample(HttpServletRequest request, HttpServletResponse response) {
logger.debug("env : {}", environment.getActiveProfiles()[0]);
SampleBean sampleBean = sampleService.getSample();
logger.debug("resultData : {}", sampleBean.getId());
return "HELLO! SAMPLE.";
}