您的位置:首页 > 其它

Swagger框架学习分享

2016-06-13 17:01 323 查看



转至元数据结尾

Created and last modified by 刘新宇 大约1分钟以前

转至元数据起始



一、背景介绍

1.1.项目简介
1.2.code
repository
1.3.演示项目

二、开发准备

2.1.环境准备
2.2.项目搭建

2.2.1.jar仓库
2.2.2.相关依赖
2.2.3.编写配置文件
2.2.4.与swagger-ui集成
2.6.5.Controller配置
2.2.6.启动中间件
2.2.7.需求定制

三、学习感想


一、背景介绍


1.1.项目简介

Swagger项目是由Dilip Krishnan和Adrian Kelly等人维护开发的一个为Spring Web MVC 项目提供方法文档的一个框架。该框架最主要的功能是将Controller的方法进行可视化的展现,像方法注释,方法参数,方法返回值等都提供了相应的用户界面,尤其是对JSON参数的支持。同时可以结合swagger-ui可以对用户界面进行不同程度的定制,也可以对方法进行一个简单的测试。


1.2.code repository

github:https://github.com/springdox/springdox
maven:http://www.mvnrepository.com/artifact/com.mangofactory/swagger-springmvc


1.3.演示项目

官方:https://github.com/adrianbk/swagger-springmvc-demo
民间:https://github.com/qq291462491/bugkillers


二、开发准备


2.1.环境准备

idea intellij 13+
Oracle java 1.6
Gradle 2.0 +


2.2.项目搭建


2.2.1.jar仓库

Maven

Gradle


2.2.2.相关依赖

As of v0.9.5 all dependencies on scala have been removed.
Spring 3.2.x or above
jackson 2.4.4
guava 15.0


2.2.3.编写配置文件

编写一个Java文件,并使用注解:

@Configuration 配置注解,自动在本类上下文加载一些环境变量信息
@EnableWebMvc
@EnableSwagger 使swagger生效
@ComponentScan("com.myapp.packages") 需要扫描的包路径

示例:

也可以自己不写配置类,直接使用默认的实现类,在Spring的配置文件中共配置:(不推荐)


2.2.4.与swagger-ui集成

方式一:

Note: Only use this option if you don‘t need to customize any of the swagger-ui static content, otherwise use option 2.
Use the web-jar which packages all of the swagger-ui static content.
Requires that your app is using the servlet 3 specification.
For non-spring boot applications some extra spring configuration (ResourceHandler‘s) is required. See: https://github.com/adrianbk/swagger-springmvc-demo/tree/master/swagger-ui

方式二:(推荐)

Manually copy all of the static content swagger-ui‘s dist directory (https://github.com/wordnik/swagger-ui/tree/master/dist)
Provide the necessary view resolvers and resource handlers to serve the static content.
Consult the spring documentation on serving static resources.

The following is one way to serve static content from /src/main/webapp


2.6.5.Controller配置

使用注解对Controller进行配置:

@Api 配置方法API
@ApiOperation API的操作 GET PUT DELETE POST
@ApiParam API的方法参数描述

示例Controller:


2.2.6.启动中间件

项目配置了Jetty或者Tomcat等Web容器的话,在对应的Controller配置好的话就可以启动看效果了。

访问本机:http://127.0.0.1:9081/api

远程示例:http://115.29.170.213/api


2.2.7.需求定制

分组信息定制
Url定制
Http相应定制


三、学习感想

Swagger很好的为我们在开发RESTful框架应用时,前后台分离的情况下提供了很有效的解决方案,上手迅速,操作简单,界面精简,功能完善,满足各种定制化的需求,是在使用Spring MVC做Web开发时的不二选择。通过对swagger的学习,增强了英语交流的能力,改变了以前的学习方法,收获了很多,同时也也得感谢国外友人的悉心帮助~技术无国界~


在公司的Wiki上写的博文,因为外面访问不了公司的内网,故贴过来给需要的小伙伴们分享一下。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Swagger