记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情。也许多点,也许少点。甚至,接口总是需要适应新需求的,修改了,增加了,这份文档维护起来就很困难了。于是发现了swagger,自动生成文档的工具。
因为自强所以自信。swagger官方更新很给力,各种版本的更新都有。swagger会扫描配置的API文档格式自动生成一份json数据,而swagger官方也提供了ui来做通常的展示,当然也支持自定义ui的。不过对后端开发者来说,能用就可以了,官方就可以了。
最强的是,不仅展示API,而且可以调用访问,只要输入参数既可以try it out.
网上很多文章使用的 maven方式集成swagger。
io.springfox
springfox-swagger2
${springfox-version}
io.springfox
springfox-swagger-ui
${springfox-version}
本项目中SpringMVC用到的jars也就这几个,笔者是手动配置的jar。一个一个下载。
SpringMVC配置文件中,配置swagger。
笔者项目中,这里不需要再次注入,官方示例中是需要注入的。
编写swagger启动配置文件。
package com.fh.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
@Configuration
@EnableWebMvc
@EnableSwagger
public class MySwaggerConfig {
@Autowired
private SpringSwaggerConfig springSwaggerConfig;
/**
* Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
* framework - allowing for multiple swagger groups i.e. same code base
* multiple swagger resource listings.
*/
@Bean
public SwaggerSpringMvcPlugin customImplementation()
{
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).
apiInfo(apiInfo()).
includePatterns(".*?");
}
private ApiInfo apiInfo()
{
ApiInfo apiInfo = new ApiInfo(
"专利管理系统在线API",
"专利管理系统在线API及接口在线管理,方便开发人员快速寻找接口和测试接口,接口统一命名为/api/模块/,
项目总指挥:王景云(15102729618)
开发组成员:李天元(13871441419),李小攀,刘阳,江明智
前端开发组成员:陈龙,王浩,魏峰",
"My Apps API terms of service",
"575110796@qq.com",
"My Apps API Licence Type",
"My Apps API License URL");
return apiInfo;
}
}
swagger-ui静态资源可以去swagger官网下载。笔者用的最新版。
配置静态资源的访问
如果项目中有权限设置的,需要将swagger/index.html 页面中生成api文档的地址过滤,不受限制,否则访问不了。
到此位置,基本配置结束。启动项目。就可以访问了。
Jars下载地址: