![[SpringBoot] Swagger 3.x 적용 [SpringBoot] Swagger 3.x 적용](http://t1.daumcdn.net/tistory_admin/static/images/xBoxReplace_250.png)
1. 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>
2. application.properties
documentationPluginsBootstrapper 빈 관련 오류를 막기 위해 다음을 추가한다.
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
3. SwaggerConfiguration Class
@Configuration, @EnableSwagger2 어노테이션을 추가한 configuration class를 만든다.
consumes(Set<String> consumes) | parameter content type을 설정한다. |
produces(Set<String>produces) | response content type을 설정한다. |
apiInfo(ApiInfo apiInfo) | ApiInfo는 swagger 관리 클래스다. 제목, 설명, 저작권, 버전 등을 설정한다. |
groupName(String groupName) | Docket이 여러개라면 그룹 이름이 필요하다. default 값은 "default"다. |
apis(Predicate<RequestHandler> selector) | 컨트롤러의 주소를 가져온다. 나는 RequestHandlerSelectors.basePackage를 이용해서 컨트롤러의 위치를 설정했다. |
paths(Predicate<RequestHandler> selector) | 주소를 설정한다. 예를 들어 controller의 requestmapping 주소가 "/user"라면 paths(regex("/user/.*"))라고 설정하고, 주소가 "/"라면 paths(regex("/.*")라고 설정하면 된다. |
@Configuration @EnableSwagger2 public class SwaggerConfiguration { private String version = "V1";//버전 private String title = "제목 " + version;//제목 @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .consumes(getConsumeContentTypes()) .produces(getProduceContentTypes()) .apiInfo(apiInfo()) .groupName(version).select() .apis(RequestHandlerSelectors.basePackage("com.__.___.controller")) .paths(regex("주소")).build() .useDefaultResponseMessages(false); } }
아래 코드에 ConsumeContentType, ProduceContentType, ApiInfo를 어떻게 설정했는지 내가 사용한 것만 작성했다.
private Set<String> getConsumeContentTypes() { Set<String> consumes = new HashSet<>(); consumes.add("application/json;charset=UTF-8"); consumes.add("application/xml;charset=UTF-8"); consumes.add("application/x-www-form-urlencoded"); return consumes; } private Set<String> getProduceContentTypes() { Set<String> produces = new HashSet<>(); produces.add("application/json;charset=UTF-8"); return produces; } private ApiInfo apiInfo() { return new ApiInfoBuilder().title(title) .description("html태그를 이용한 설명 작성") .contact(new Contact("이름", "url", "이메일")) .license("라이센스 링크제목") .licenseUrl("라이센스 링크") .version("버전설정").build(); }
자세한 사항은 https://springfox.github.io/springfox/docs/current/#docket-spring-java-configuration 를 참고하면 된다. xml로 configuration을 작성하려면 https://springfox.github.io/springfox/docs/current/#docket-xml-configuration 글을 참고하면 되겠다.
4. RestController Class
본인이 작성한 restcontroller에 @Api("설명")을 붙인다.
메소드 하나하나에는 @ApiOperation(value="제목", notes="설명")을 붙일 수 있다.
@ApiResponses에는 @ApiResponse(code=HTTP코드번호, message="설명")들을 넣을 수 있다.
@Api("컨트롤러제목 v1") public class AdminController { private static final Logger logger = LoggerFactory.getLogger(AdminController.class); @ApiOperation(value = "회원목록", notes = "회원 <big>전체 목록</big> 반환.") @ApiResponses({ @ApiResponse(code=404, message="주소오류!"), @ApiResponse(code=405, message="지원하지 않는 메소드 호출"), @ApiResponse(code=500, message="서버에러!"), @ApiResponse(code=200, message="회원 목록 정상 처리") }) @GetMapping(value = "/user") public ResponseEntity<?> userList() { //..... } }
5. Dto Class
4번 restcontroller가 사용하는 dto에 설명을 작성할 수 있다.
클래스 위에 @ApiModel(value="제목", description="설명")을 쓰고
각 변수 위에 @ApiModelProperty(value="설명")을 작성하면 된다.
@ApiModel(value="MemberDto(회원정보)", description="회원아이디 등 정보를 가진 클래스") public class MemberDto { @ApiModelProperty(value="회원 이름") private String userName; }
6. url 확인
swagger 3.x 버전 url은 localhost:{port번호}/{context-path}/swagger-ui/index.html이다. 스프링부트는 기본적으로 context-path가 /이기 때문에 적지 않아도 된다.
'기록 > BACKEND' 카테고리의 다른 글
[SpringBoot] 자바 메일 보내기 (0) | 2022.07.21 |
---|---|
[SpringBoot] 따로 개발한 springboot와 vue 합치기 (0) | 2022.06.29 |
[SpringBoot] MySql & MyBatis 설정하기 (0) | 2022.05.09 |
[Spring] Annotation 정리 (0) | 2022.05.03 |
[Spring] 프로젝트 실행 순서 (0) | 2022.05.02 |
댓글