##swagger Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful风格的Web服务。推荐-翻译
swagger=specification+tools(前端用户界面、底层代码库、商业API管理解决方案)
swagger规范之于REST 类比 WSDL之于WebService
##swagger规范
The Swagger specification defines a set of files required to describe such an API. These files can then be used by the Swagger-UI project to display the API and Swagger-Codegen to generate clients in various languages. Additional utilities can also take advantage of the resulting files, such as testing tools.
It includes information on how to define paths, parameters, responses, models, security and more
##swagger工具 swagger UI:无依赖的HTML、JS和CSS的应用,根据swagger的json文件自动生成api文档和沙箱测试。
- 把swagger ui的dist目录以第三方js组件的方式添加到web应用;
- 修改index.html中window.swaggerUi =new SwaggerUi({});里的初始化参数url为swagger json文件路径,可以是普通js文件,也可以是后台动态生成json;
- 本地化:在index.html里添加lang/translator.js和lang/zh-cn.js;
swagger editor: swagger规范文件编辑器
swagger-core: Swagger implementation for Java/Scala. Has integration with JAX-RS (Jersey, Resteasy, CXF...), Servlets and Play Framework.
binder-swagger-java: binder-swagger-java was designed to help construct the swagger object, corresponding to swagger.json, and let it accessible from swagger ui or other http visitors.
springfox: Integrates with Spring MVC with support for Swagger 1.2 and Swagger 2.0 spec.
swagger-maven-plugin:Support Swagger Spec 2.0, integrate with JAX-RS & Spring MVC project, and easily generate swagger.json & a static document during build phase.
##swagger-maven-plugin使用
swagger-maven-plugin用来扫描类生成swagger.json规范。基于支持JAX-RS和SpringMVC。注意:
- 扫描@Api注解的类;
- 只有@ApiOperation,@RequestMapping注解并带有method属性的方法才会被识别;
- 带@ApiParam注解的参数才会被识别;
- SpringMVC扫描参数识别类型规则:逻辑在SpringSwaggerExtension
| springMVC注解 | 参数类型 |
|---------------|---------------------------|
| RequestParam |QueryParameter query |
| PathVariable |PathParameter path |
| RequestHeader |HeaderParameter header |
| CookieValue |CookieParameter cookie |
| RequestPart |FormParameter formData|
| ModelAttribute|QueryParameter query |
| 其他 | BodyParameter body | - maven插件的配置参数需要包括:info, info/title, info/version, locations(需要生成规范的类名/包名)
- 参数的schema属性是object类型并properties为空,swaggerui会报错:如参数是Object类型,
##swagger-maven-plugin修改扩展 swaggerUI生成的doc文档比javadoc文档更容易在团队中传阅交流。
工程在集成构建时把生成的swagger规范文件上传到指定目录swagger-dir,带swaggerUI的基础web应用会扫描swagger-dir目录,返回swagger.json的列表到页面。swagger-maven-plugin只针对REST API,对于普通API需要另做处理:新增继承AbstractDocumentSource的PSMavenDocumentSource,继承AbstractReader的PSApiReader。
修改点:
- 默认增加一个类全名的tag标签;
- springMVC默认method=post,如果@RequstMapping中没有写明method的方法也可以识别;
- 对于非REST的API,默认path为方法签名,默认method为post
- @ApiParam没写明name属性则自动识别,在此使用
String[] org.springframework.core.ParameterNameDiscoverer.getParameterNames(Method method)
- 增加插件配置参数:swaggerFileName指定生成的swagger规范的文件名
修改后swagger-maven-plugin代码
修改后swagger-maven-plugindemo