Swagger는 편안한 스타일의 웹 서비스를 생성, 설명, 호출 및 시각화하기위한 표준화되고 완전한 프레임 워크입니다. 전반적인 목표는 클라이언트 및 파일 시스템을 서버와 동일한 속도로 업데이트하는 것입니다. 파일 방법, 매개 변수 및 모델은 서버 측 코드에 엄격하게 통합되어 API가 항상 동기화 될 수 있습니다.
Swagger는 강력한 API를 배포하고 관리하고 사용하기가 더 쉽지 않았습니다. 좋아요, 위는 공식 성명서입니다. 직접 복사했습니다. 제 생각에 Swagger는 인터페이스 문서 관리자입니다. 과거에는 일반적으로 세계에서 인터페이스를 썼지 만 테스트 할 때 타사 도구에 의존 해야하는 문제가 있습니다. Get 인터페이스는 괜찮으며 브라우저에서 직접 열립니다. 게시물은 다른 도구에만 의존 할 수 있습니다. Swagger는 코드의 주석을 통해 인터페이스 문서 (Javaee)를 직접 생성 할 수 있습니다. 대부분의 사람들은이 방법을 사용하며 프로젝트에 직접 통합되어 회원을 촉진하고 직접 테스트 할 수도 있습니다. 또한 Swagger의 인터페이스도 좋습니다. 어쩌면 이것이 내가 Swagger를 사용하기로 선택한 이유 일 것입니다. 공무원이 직접 언급 한 편안한 스타일은 편안하지 않습니다. 스타일 인터페이스도 사용할 수 있습니다. 물론 Swagger가 인터페이스 지침을 수동으로 작성하는 또 다른 방법이 있습니다. Swagger 인터페이스 주석이 코드에 추가되면 코드의 양이 여전히 많이 증가하기 때문에 코드에는 코드 만 코드 만 있다는 것입니다. 물론, 단점은 코드를 수정 한 후 인터페이스 문서를 변경해야한다는 것입니다.
SpringMVC는 Springfox-Swagger2 및 Springfox-Swagger-UI를 통합하는 것이 매우 간단합니다.
(1) POM에 종속성을 추가하십시오
<pectionency> <groupid> io.springfox </groupid> <artifactid> springfox-swagger-ui </artifactid> <version> $ {springfox-swagger.version} </version> </dependency> <pelevency> <groupid> io.springfox </groupid> <artifactid> springfox> <버전> $ {springfox-swagger.version} </version> </fectionency>(2) Swagger 구성 클래스 추가 :
@configuration @enablebsger2 @enablewebmvc @componentscan ( "com.xxx.controller") public class swaggerconfig {} 그런 다음 http : //localhost/swagger-ui.html을 통해 프로젝트의 모든 인터페이스 정보를 볼 수 있으며 http : // localhost/v2/api-docs를 통해 JSON 데이터를 볼 수 있습니다.
그러나 제작 환경에서 이러한 API 문서를 어떻게 비활성화합니까? 나는 여러 가지 방법을 시도했고 마침내 간단하고 실용적인 방법을 찾았습니다.
@configuration @enablebsger2 @enablewebmvc @componentscan ( "com.xxx.controller") public class swaggerconfig {@autowired configservice configservice; @bean public docket customDocket () {if (configservice.getServerenv () == serverenvenum.online) {return new Docket (d .짓다(); } else {return new Docket (DocumentationType.wagger_2) .apiinfo (apiinfo ()); }} private apiinfo apiinfo () {새로운 apiinfobuilder () .title ( "xxx system") .description ( "xxx system interface") .license ( "") .licenseurl ( ") .termsofserviceurl (" "). .짓다(); } private apiinfo apiinfoonline () {새로운 apiinfobuilder () .title ( "") .description ( "") .license ( "") .licenseurl ( "") .termsofserviceurl ( "") .contact (새 접촉 ( "" ",") }} 페이지 http : //localhost/swagger-ui.html 페이지에 여전히 액세스 할 수 있지만 http : // localhost/v2/api-docs를 포함한 내용은 없습니다.
더 나은 방법이 있어야합니다!
참조 : //www.vevb.com/article/135312.htm
Swagger는 SpringMVC와 동일한 상황이어야하며 SpringMVC는 Spring의 하위 텍스트 일뿐입니다. Swagger가 Spring Context Load를 사용하면 Swagger의 URL을 SpringMVC 인터셉터와 함께 가로 채지 못합니다!
따라서 두 가지 해결책이 있습니다.
주석을 사용하는 경우 :
(1) 스프링 -MVC 구성 :
<!-주석을 사용하여 Bean을 자동으로 등록하고 @controller 만 스캔합니다-> <context : component-scan base-package = "com.inspur.eyun.yunbx"use-default-filters = "false"> <!-기본-패키지가 여러 인 경우 "-> <context" expression = "org.springframework.steretype.controller"/> <context : 포함 필터 유형 = "할당 가능한"expression = "com.inspur.eyun.yunbx.swagger.waggerconfig"/> </context : component-scan>
Swagger 구성을 추가해야하며 동시에 다음과 같습니다.
(2) 스프링 구성 :
<!-패키지 스캔, 주석 관련-> <문맥 : 구성 요소 스캔 기본-패키지 = "com.inspur.eyun.yunbx"> <context : 컨텍스트 : 제외 필터 유형 = "주석"expression = "org.springframework.steretype.controller"/> context : "할당 가능한" expression = "com.inspur.eyun.yunbx.wagger.waggerConfig"/> </context : component-scan>
Swagger 제외에주의하십시오
(3) Swagger 구성 :
@configuration @enablebsger2 @enablewebmvc @componentscan ( "com.inspur.eyun.yunbx.controller") public class swaggerconfig {}@Configuration 주석에 유의하십시오.
물론 더 권장되는 방법은 XML 구성 방법을 사용하는 것입니다.이 방법으로 Swagger 종속성 패키지를 소개 할 필요가 없기 때문입니다.
(1) 스프링 -MVC 구성 :
<!-주석을 사용하여 Bean을 자동으로 등록하고 @controller 만 스캔합니다-> <context : component-scan base-package = "com.inspur.eyun.yunbx"use-default-filters = "false"> <!-기본-패키지가 여러 인 경우 "-> <context" expression = "org.springframework.stereotyp.controller"/> </context : component-scan> <import resource = "classpath : spring-mvc-swagger.xml"/>
Spring-MVC-Swagger.xml :
<? xml version = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xsi = "http://www.w.w3.org/2001/xmlschema-instance"xsi " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> springmvc spighgger </description> 구성, 생산 환경 빈 -> <bean /> < /beans>
참고 : Swagger를 구성 파일에 별도로 배치합니다. 온라인 환경 인 경우 파일 내용이 비어 있습니다. 오프라인 테스트 환경 인 경우 Swagger가 구성됩니다.
(2) 스프링 구성 :
<!-패키지 스캐닝, 주석 관련-> <문맥 : 구성 요소 스캔 기본-패키지 = "com.inspur.eyun.yunbx"> <context : 컨텍스트 : 제외 필터 유형 = "주석"expression = "org.springframework.stereotyp.controller"/> 컨텍스트 : content-scan>
(3) Swagger 구성 :
@enableswagger2 @enablewebmvc public class swaggerconfig {@bean public docket customDocket () {return new docket (returnype.swagger_2) .apiinfo (apiinfo ()) .apis (retureHandlersElector.basePackage ( "com.inspur.yun.yunbx.yun.yunbx.yun.yunbx. .paths (pathselectors.any ()) .build (); } private apiinfo apiinfo () {새로운 apiinfobuilder () .title ( "xxx platform") .description ( "xxx 플랫폼 인터페이스") .license ( "") .licenseurl ( "") .termsofserviceurl ( "") .version ( "1.0.0"). .짓다(); }}참고 : 여기서 @Configuration을 제거했으며 동시에 POM을 수정하고 여러 프로파일 패키징을 구성했습니다.
pom.xml :
<!-swagger-> <pectionency> <groupId> io.springfox </groupid> <artifactid> springfox-swagger2 </artifactid> <bersion> $ {springfox-swagger.version} </version> <cope> $ {swagger.scope} </scope> <groupid> <artifactid> springfox-swagger-ui </artifactid> <cope> $ {swagger.scope} </scope> <버전> $ {springfox-swagger-ui.version} </version> </fectionency>참고 : 여기서 의존하는 범위는 동적으로 설정됩니다. 온라인 환경 인 경우 제공 범위를 설정할 수 있습니다.
<profiles> <profile> <id> dev </id> <properties> <profiles.Active> dev> dev </profiles.Active.Active.Acgger.scope> compile </swagger.scope> </properties> <ctiveBydefault> true </activeBydefault> </captivation> <profile> <id> <prople>> <propeies>> <id>> <id>> <id> <id> <id>. <profiles.active> test </profiles.active> <swagger.scope> compile </swagger.scope> </properties> </profile> <propect> <id> 온라인 </id> <properties> <properties> <propiles.active> test </profiles.active> <swagger.scope> compile. <id> 온라인 </id> <properties> <profiles.active> 온라인 </profiles.active> <swagger.scope> 제공 </swagger.scope> </properties> </profile> </profiles> </profiles>
다른 프로파일을 통해 Swagger의 종속성에 대한 다른 범위를 설정하십시오!
참고 : Springfox-Swagger.version = 2.7.0에는 버그가 있으며 낮은 버전 2.6.1을 사용할 수 있습니다. 너무 빌어 먹을 속임수!
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.