该示例基于以前的实战系列,若是公司框架是使用JDK7以上及其Spring+MyBatis+SpringMVC/Spring+MyBatis Plus+SpringMVC可直接参考该实例。java
不过建议最好采用的是JDK8+Spring+MyBatis Plus+SpringMVC,由于本示例就是基于这个。web
之因此集成SpringFox+Swagger2,由于该特性因为以前的单SpringMVC集成Swagger。spring
这一点,后面我会专门讲到的。api
1、导入依赖浏览器
<!-- swagger api文档管理 --> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-models</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>com.wordnik</groupId> <artifactId>swagger-annotations</artifactId> <version>1.3.11</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency> <!-- 集成springfox --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
2、编写SwaggerConfig.javaspring-mvc
package com.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; 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; /** * * @author yc */ @Configuration @EnableSwagger2 public class SwaggerConfig{ @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("接口API管理文档") .description("HTTP对外开放接口") .version("1.0.0") .termsOfServiceUrl("http://www.test.com") .license("LICENSE") .licenseUrl("http://www.test.com") .build(); } }
3、在spring-mvc.xml文件补充该beanmvc
顾名思义该Bean的做用就是集成Swagger集成Spring框架
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />
若是不添加该Bean就会出现以下状况:ui
另外还有就是配置好bean运行项目后出现如图状况:google
描述的状况是:正在获取资源,不过须要延迟一段时间
获取资源列表,加载缓慢,打不开,一般是浏览器的缘故,我用IE和火狐均可打开看到正常的API接口文档,可是用Google浏览器就始终打不开,这点目前不知道是什么缘由,有待研究。
另外关于swagger版本问题,若是是SpringMVC整合Swagger的话,建议使用2以上,3如下的版本,否则会出现以下图所示状况:
Springmvc整合swagger的3以上版本出现上述问题
缘由:版本太低不能采用
解决方案:使用低版本swagger便可恢复正常
建议使用2.2.10的swagger版本
若是是SpringBoot的话,直接使用swagger3以上的版本。SpringBoot使用swagger高版本不存在这种问题,以前我已经试验过了。