외부 인터페이스 문서는 항상 비교적 원시적이며 기본적으로 필기 된 문서가 전달됩니다. 최근에 나는 새로운 장난감을 발견하여 인터페이스에서 많은 문제를 절약 할 수 있습니다.
Swagger는 편리한 API 문서 프레임 워크입니다. 필기 문서의 일방적 및 오류 동작을 피하면서 가장 포괄적 인 방식으로 다른 개발자에게 인터페이스 유형을 표시 할 수 있습니다.
현재 Swagger와 Swagger2의 두 가지 유형이 있습니다. 1은 더 번거 롭기 때문에 사용하는 것을 고려하지 않습니다. 이 기사는 주로 Swagger2를 외부 인터페이스로 사용하는 두 가지 방법을 기록합니다. 나중에 확인하십시오.
1. 전통적인 SpringMVC를 사용하여 Swagger2를 통합하십시오
1. Maven 의존성
<!-SpringFox 종속성-> <pectionency> <groupId> com.fasterXML.jackson.core </groupId> <artifactid> Jackson-Core </artifactid> <bersion> 2.8.0 </dependency> <pection> <groupid> com.fasterxml.jackson.core <artifactid> <버전> 2.6.3 </version> </dependency> <pectomency> <groupid> com.fasterxml.jackson.core </groupid> <artifactid> jackson-annotations </artifactid> <버전> 2.6.3 </version> </dependency> <groupid> io.springfox> <아티 팩트> Springfox-Swagger2 </artifactid> <bersion> 2.4.0 </version> </dependency> <pectomency> <groupId> io.springfox </groupId> <artifactID> SpringFox-Swagger-ui </artifactid> <4.0 </version> </dependency>
2. Spring-MVC.xml에서 정적 매핑 구성을 추가합니다 (실제로 프로젝트에서 이것을 제거 할 수 있습니다. 상황이 무엇인지 모르겠습니다) :
<!-Swagger 정적 파일 경로-> <mvc : 자원 위치 = "classpath :/meta-inf/resources/"mapping = "swagger-ui.html"/> <mvc : mvc : "classpath :/meta-inf/resources/webjars/"mapping = "/webjars/**"/>
참고 : 기본 SpringMVC 구성을 게시하지 않습니다. Swagger-ui.html 인터페이스가 나오면 비어 있으면 Web.xml에서 인터셉터 구성을 확인하십시오. 먼저 SpringMVC를 가로 채고 인터페이스가 표시됩니다.
3. 그런 다음 Swagger2의 구성 클래스가 있습니다.
@configuration @enableswagger2public class swaggerconfig 확장 webmvcconfigurationsupport {@bean public docket createrestapi () {return new docket (documentationtype.wagger_2) .apiinfo (apiinfo ()) .select (). .apis (requestHandlersElectors.basePackage ( "net.laoyeyey.yyblog")) .paths (pathselectors.any ()) .build (); } private apiinfo apiinfo () {return new apiinfobuilder () .Title ( "yyblog project RESTFUL API") .DESCREPTION ( "YYBLOG Project API 인터페이스 문서") .version ( "1.0") .Build (); }}참고 : PathSelectors.none ()에서 경로를 조정할 수있는 경우 모든 인터페이스 정보를 표시하지는 않습니다.
4. 인터페이스 정보 구성
즉, SpringMVC 컨트롤러에서 관련 인터페이스 정보를 구성하십시오
@controller@requestMapping (value = "aitou")@api (description = "테스트 서비스-계산 정보 쿼리") 공개 클래스 일일 정리 datacontroller {logger logger = logger.getLogger (DailyOperationDataconTroller.class); @autowired private dailyoperationdataservice dailyOperationDataservice; / * * * @apioperation (value = "인터페이스 설명", httpmethod = "인터페이스 요청 메소드", 응답 = "인터페이스 반환 매개 변수 유형", notes = "인터페이스 릴리스 노트" * @apiparam " * @apiparam" * @apiparam " = {requestMethod.post, requestMethod.get}, value = "/query/dailydata/{dataDate}") @ResponseBody public dailyOperationDatAdto getDailyReportByDatAdate ( "DataDate") 문자열 Datadate) {DailyOperationDataService.get Daverdate (DataDate); e) {logger.error (e.getMessage (), e);참고 : 일반적으로 Swagger2는 스캔 패키지 아래에 모든 인터페이스를 표시합니다. 여기서는 너무 많은 인터페이스를 표시하지 않기 위해 별도의 패키지가되는 외부 인터페이스입니다. 물론 인터페이스 방법은 또한 표시를 방지 할 수 있습니다. 아래의 관련 주석을 볼 수 있습니다.
일반적으로 사용되는 일부 메모
@api : 수업의 기능을 설명하기 위해 수업에서 사용
@apioperation : 방법의 기능을 설명하기 위해 방법에 사용
@apiimplicitparams : 메소드에 매개 변수 설명 세트를 포함하는 데 사용됩니다.
@apiimplicitparam : @apiimplicitparams 주석에 사용, 요청 매개 변수의 다양한 측면을 지정합니다. 매개 변수 paramtype : 매개 변수를 배치 할 위치 ・ 헤더 -> 요청 매개 변수 : @requestheader
・ 쿼리 -> 요청 매개 변수 획득 : @requestparam
・ 경로 (편안한 인터페이스 용) -> 요청 매개 변수 가져 오기 : @PathVarible
・ 신체 (일반적으로 사용되지 않음)
・ 양식 (일반적으로 사용되지 않음)
이름 : 매개 변수 이름 데이터 유형 : 매개 변수 유형 필수 : 매개 변수를 전달 해야하는지 값 : 매개 변수 의미 기본값 : 매개 변수 기본값
@apiresponses : 응답 세트를 나타내는 데 사용됩니다
@apiresponse : @apiresponses에서 사용되며 일반적으로 오류 응답 코드를 표현하는 데 사용됩니다. 400과 같은 숫자
메시지 : "요청 매개 변수가 채워지지 않음"과 같은 메시지
응답 : 예외를 던지는 클래스
@apiparam : 단일 매개 변수 설명
@apimodel : 모델의 정보를 설명하고 객체를 사용하여 매개 변수를 수신합니다 (이것은 일반적으로 게시물을 작성하고 @requestbody 시나리오를 사용하고 @apiimplicitparam 주석을 사용하여 매개 변수를 설명 할 수 없습니다).
@apimodelProperty : 모델의 속성을 설명하십시오
@apiproperty : 객체를 사용하여 매개 변수를받을 때 객체 필드를 설명하십시오.
@apiignore :이 주석을 사용 하여이 API를 무시하십시오
기본적으로 위의 모든 것입니다. 매우 쉽지 않습니까? 아래의 효과 그림을 보자
2. SpringBoot를 사용하여 Swagger2를 통합하십시오
위에서 언급 한 것은 Swagger2를 통합하기 위해 기존의 SpringMVC를 사용하여 사용했습니다. 최근 인기있는 SpringBoot 방법에 대해 이야기 해 봅시다. 실제로 원칙은 동일합니다.
1. Maven 의존성
<!-Springfox 종속성-> <pectionency> <groupId> io.springfox </groupId> <artifactid> springfox-swagger2 </artifactid> <bersion> 2.7.0 </dependency> <pectionency> <groupId> io.springfox </groupid> <artifactid> springfox-ui-ui-ui </artifactid> <버전> 2.7.0 </버전> </의존성>
이것은 SpringBoot를 사용하여 최근에 쓴 개인 프로젝트의 내부 사용이며 사용 된 버전은 버전에서 사용됩니다.
2. 정적 자원 구성을 추가하십시오
@ConfigurationPublic Class WebMvcConfig 확장 webmvcconfigureradapter {/ ** * 정적 리소스 경로와 파일을 업로드하는 경로 * * @param registry */ @override public void addresourceHandlers (ResourceHandlerRegistry) { registry.addresourceHandler ( "/static/**"). addResourcelocations ( "classPath :/static/"); registry.addresourceHandler ( "/upload/**"). addResourcelocations (Environment.getProperty ( "spring.resources.static-locations"); /*swagger-ui*/registry.addresourcehandler ( "swagger-ui.html"). addresourcelocations ( "classpath :/meta-inf/resources/"); registry.addresourcehandler ( "/webjars/**"). addResourcelocations ( "classpath :/meta-inf/resources/webjars/"); }}실제로, 그것은 마지막 두 문장 일뿐입니다. 이를 구성하지 않으면 Swagger-UI.html을 방문하면 500 또는 404의 오류가 표시됩니다. 기억할 수 없다면 404 여야합니다.
3. Swagger2 구성 클래스
위와 마찬가지로 기본적으로 차이가 없습니다
@configuration@enablebsger2@enableWagger2@enableWebmvcpublic class swaggerConfig 확장 webMvcConfigUrationSupport {@bean public docket createrestapi () {return new docket (documentationtype.swagger_2) .apiinfo (apiinfo ()) .select (). .apis (requestHandlersElector.basePackage ( "net.laoyeye.yyblog.web.frontend") .paths (pathselectors.none ()) .build (); } private apiinfo apiinfo () {return new apiinfobuilder () .title ( "yyblog project RESTFUL API") .Description ( "yyblog project api 인터페이스 문서") .version ( "1.0") .Build (); }}위의 경로에 문제가 있습니다. 사본은 직접 API를 표시하지 않습니다 (#^.^#)
4. 인터페이스 구성
/*** 프론트 데스크 기사 컨트롤러* @Author Grandpa 편의점* @WebSite 2018 년 5 월 5 일* @website www.laoyeye.net*/ @api (description = "article query") @controller @requestmapping ( "/article") 공개 클래스 ArticleController {@autow private articleservice; @autowired 개인 설정 서비스 설정 서비스; @autowired Private Cateservice Cateservice; @autowired private tagreferservice tagreferservice; @autowired private userervice userservice; @autowired private articlepaper articlemapper; @autowired private CommentService CommentService; @apioperation (value = "article query interface") @apiimplicitparam (name = "id", value = "article id", required = true, datatype = "long") @getmapping ( "/{id}") public String index (모델 모델, @pathvariable ( "id") long id) {try artevice.updateviewsbyid (id); } catch (예외 무시) {} 목록 <설정> 설정 = settingservice.listall (); map <string, object> map = new Hashmap <String, Object> (); for (설정 : 설정) {map.put (setting.getCode (), setting.getValue ()); } article article = articleService.getArticleByid (id); model.adtattribute ( "설정",지도); model.addattribute ( "catelist", categoryService.listallcate ()); model.addattribute ( "기사", 기사); Model.AdDattribute ( "tags", tagreferservice.listNameByArticleId (article.getId ()); Model.AdDattribute ( "저자", userVice.getNickNameById (article.getAuthorid ())); // change model.addattribute ( "articles", articlemapper.listarticleBytitle (null)); Model.AdDattribute ( "유사한", articleMapper.ListArticleByTitle (null)); CommentQuery Query = 새로운 CommentQuery (); query.setLimit (10); query.setpage (1); query.setarticleid (id); model.addattribute ( "comment", commentservice.listcommentByArticleId (query)); "프론트 엔드/기사"를 반환합니다. } @apioperation (value = "ArticleComment Query Interface") @postmapping ( "/comment") @ResponseBody public dataGridResult 댓글 (CommentQuery Query) {// 기본값 Query.setLimit (10)를 설정합니다. return CommentService.listCommentByArticleId (query); } @apioperation (value = "articlelid") @apiimplicitparam (name = "articleid", value = "article id", require =, dataType = "long") @postmapping ( "/apportove") @ResponseBody public yyBlogresult alprove (@requestparam long article) }}마지막으로 위와 동일한 렌더링이 있습니다.
pathselectors.none () 일 때
pathselectors.any ()가있을 때
인터페이스 컨텐츠가 렌더링인지 여부는 분명하며 매우 간결하고 명확합니다.
마지막으로 Swagger 문서의 길을 말하는 것을 잊어 버린 것 같습니다.
프로젝트가 루트 디렉토리에있는 경우 http : // localhost : 8080/swagger-ui.html
루트 디렉토리가 아닌 경우 http : // localhost : 8080/프로젝트 이름/swagger-ui.html입니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.