一、背景介绍
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
1 | <repositories> |
Gradle
1 | repositories { |
2.2.2.相关依赖
1 | Spring 3.2.x or above |
2.2.3.编写配置文件
编写一个Java文件,并使用注解:
1 | @Configuration 配置注解,自动在本类上下文加载一些环境变量信息 |
也可以自己不写配置类,直接使用默认的实现类,在Spring的配置文件中共配置:(不推荐)
1 | <mvc:annotation-driven/> <!-- Required so swagger-springmvc can access spring's RequestMappingHandlerMapping --> |
2.2.4.与swagger-ui集成
方式一:1
2
3
4Note: 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
1 | dependencies { |
方式二:(推荐)1
2
3
4Manually 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
1 | <!-- Direct static mappings --> |
2.6.5.Controller配置
使用注解对Controller进行配置:
1 | @Api 配置方法API |
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的学习,增强了英语交流的能力,改变了以前的学习方法,收获了很多,同时也也得感谢国外友人的悉心帮助~技术无国界~
3.1 Guava工具类的使用 http://ifeve.com/google-guava/
Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] 、缓存 [caching] 、原生类型支持 [primitives support] 、并发库 [concurrency libraries] 、通用注解 [common annotations] 、字符串处理 [string processing] 、I/O 等等
3.2 Gradle构建工具的使用 http://ifeve.com/google-guava/
配置更加简洁,支持Maven,好多开源项目已经从Maven转到Gradle。
3.3 Groovy语言 http://groovy.codehaus.org/User+Guide
和scala、clojure等同是在JVM上运行的脚本语言,丰富的类库,和Java互通,可以作为Java程序员的第二语言。
3.4 链式编程 (return this)
Java中类似Swagger配置文件SwaggerSpringMvcPlugin
JQuery中类似 $(“#p1”).css(“color”,”red”).slideUp(2000).slideDown(2000);
在公司的Wiki上写的博文,因为外面访问不了公司的内网,故贴过来给需要的小伙伴们分享一下,有疑问的可以随时交流。