1.swagger是什么?
Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。
swagger項目地址:https://github.com/swagger-api/swagger-ui
2.springMVC中加入swagger2
2.1、使用maven導入jar包,pom.xml增加:
1 <dependency> 2 <groupId>io.springfox</groupId> 3 <artifactId>springfox-swagger2</artifactId> 4 <version>2.4.0</version> 5 </dependency> 6 <dependency> 7 <groupId>io.springfox</groupId> 8 <artifactId>springfox-swagger-ui</artifactId> 9 <version>2.4.0</version> 10 </dependency>
2.2、增加swagger的配置類,主要是自定義文檔的來源、標題掃描的位置or路徑or接口
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import springfox.documentation.builders.ApiInfoBuilder; 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 @EnableWebMvc @EnableSwagger2 public class SwaggerConfig{ @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("監管平台-國際版API") .description("http不對外開放接口") .version("1.0.0") .termsOfServiceUrl("http://xxx.xxx.com") .license("假裝這里有license") .licenseUrl("http://xxx.xxx.com") .build(); } }
2.3、在spring-mvc中加載自定義配置類,以及攔截其中增加靜態資源訪問控制。
<bean class="com.incomrecycle.itrms.config.SwaggerConfig" /> <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" /> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
2.4、修改web.xml
因為在swagger中程序會根據swagger注解將接口描述為json,然后swager讀取json數據 然后編排成接口文檔;所以需要將這些接口路徑配置進來。
因為有些springMVC只對*.do配置,並沒有對swagger進行配置。所以如果只完成上面的步驟swagger是找不到接口信息的;
所以在web.xml中將原來springMVC Servlet攔截路徑由:
<servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
改為:
<servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>/swagger/*</url-pattern> <url-pattern>/api-docs</url-pattern> </servlet-mapping>
這時候訪問:
http://localhost:8080/itrms/swagger/swagger-ui.html
則swagger管理界面出現如下:
swagger2 注解說明文檔
參考地址:
https://blog.csdn.net/weixin_41846320/article/details/82970204