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