Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
作用:
接口的文档在线自动生成。
功能测试。
下面通过实现一个web项目来演示Swagger的使用。
1. 新建SpringMVC项目
1.1 新建项目
新建基于maven的web项目,导入spring相关依赖如下
4.0.0
com.zang.xz
mySwagger
0.0.1-SNAPSHOT
war
mySwagger Maven Webapp
http://www.example.com
UTF-8
4.3.6.RELEASE
com.fasterxml.jackson.core
jackson-databind
2.8.9
org.springframework
spring-core
${spring.framework.version}
org.springframework
spring-context
${spring.framework.version}
org.springframework
spring-webmvc
${spring.framework.version}
mySwagger
1.2 配置web.xml和spring-mvc.xml
web.xml
Archetype Created Web Application
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
true
spring-mvc
/
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
spring-mvc.xml
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
1.3 新建entity和controller测试
为求简便,这里不集成dao层,数据直接从controller中封装返回。
Product.java
packagecom.zang.xz.entity;public classProduct {private static final long serialVersionUID = 1L;/**ID*/
privateLong id;/**产品名称*/
privateString name;/**产品型号*/
privateString productClass;/**产品ID*/
privateString productId;publicLong getId() {returnid;
}public voidsetId(Long id) {this.id =id;
}publicString getName() {returnname;<