pom
<!-- swagger2核心依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!-- swagger-ui为项目提供api展示及测试的界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
swagger配置文件
@Configuration
@EnableSwagger2
@EnableWebMvc
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("基础平台 RESTful APIs")
.description("基础平台 RESTful 风格的接口文档,内容详细,极大的减少了前后端的沟通成本,同时确保代码与文档保持高度一致,极大的减少维护文档的时间。")
.termsOfServiceUrl("http://xiachengwei5.coding.me")
.contact("Pat")
.version("1.0.0")
.build();
}
}
rest接口可有可无,附上rest api demo
@RestController
@RequestMapping("/pubpay")
@Api(value = "test")
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "test",httpMethod = "GET")
public String test() {
return "";
}
}
swagger注解及rest api知识请自行学习
mvc配置文件中配置bean及静态资源
<!-- swagger配置文件所在包-->
<context:component-scan base-package="..."/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/" />
运行tomcat,访问路径为:http://localhost:8080/swagger-ui.html
本人曾遇到的问题
swagger-ui不显示接口列表
尝试访问http://localhost:8080/v2/api-docs,得到的数据为{}
查资料得知fastjson版本问题,替换即可:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
替换为:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>