티스토리 뷰
api 명세를 위해 Spring rest docs를 도입 중 과거 서비스가 너무 레거시 하다보니 최소 사양에 못미쳐 사용을 못하는 경우 발생.
버전업하기엔 리소스가 너무 크게 소모되기에 과거 서비스에는 swagger2 사용하기로 결정.
swagger 2.9.2 버전 maven dependency 적용.
<!-- Swagger -->
<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>
Bean 등록
config class를 하나 파준후 환경 설정을 해준다.
@Configuration
@EnableSwagger2
public class Config4Swagger2 {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("kr.co.test"))
.paths(PathSelectors.ant("/api/**")) // url 필터링
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"TEST API",
"Some custom description of API.",
"0.0.1",
"Terms of service",
new Contact("test", "http://test.co.kr", null),
"License of API", "API license URL", Collections.emptyList());
}
}
basePackage() 에서 하위 검색 기준 패키지를 설정해준다.
ant() 에서 swagger 명세할 api 주소를 설정해준다. any, none 등의 메서드가 더 있다.
test할 restcontroller를 하나 생성 해주고 아래와 같이 테스트 작성.
@RestController
@RequestMapping("/api/v1")
public class TestController2 {
@GetMapping("user/search")
public Map<String, String> search() {
Map<String, String> response = new HashMap<String, String>();
response.put("name", "taehong.kim");
response.put("age", "28");
response.put("email", "xxxxxxxx@gmail.com");
return response;
}
}
서버 실행 후 http://127.0.0.1//swagger-ui.html 에 접근 해보면 정상 sawgger 페이지가 뜬다.
spring security를 함께 쓸경우에는 security config 설정에서 swagger 부분을 antMatchers 처리해줘야 한다.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/scripts/**", "/styles/**", "/images/**", "/vendor/**", "/icons/**", "/fonts/**", "/favicon.ico","/upload/**",
"/v2/api-docs", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**", "/swagger/**" ); //하단은 Swagger에서 사용되는 것을 추가
}
swagger 기본 설정은 간단하다.
다음에는 명세를 꾸미는 방법들을 작성해야 한다.
'기타 > swagger' 카테고리의 다른 글
02. swagger UI 3.0.0 - 적용 (0) | 2022.07.04 |
---|
댓글