查考链接:https://my.oschina.net/wangmengjun/blog/907679

coding地址:https://git.coding.net/conding_hjy/SpringMVC_SpringFox_Swagger.git

1、需求

  在做项目的时候,有时候需要提供其它平台(如业务平台)相关的HTTP接口,业务平台则通过开放的HTTP接口获取相关的内容,并完成自身业务~
  提供对外开放HTTP API接口,比较常用的是采用Spring MVC来完成。
  本文的目标是先搭建一个简单的Spring MVC应用,然后为Spring MVC整合SpringFox-Swagger以及SpringFox-Swagger-UI,最终,达到Spring MVC对外开放接口API文档化。

如图所示:

2、实现步骤

2.1 搭建SpringMVC工程

  2.1.1 新建Maven工程

  

  

  

2.1.2 引入Spring依赖包

完整的pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx.tutorial</groupId>
<artifactId>springfox-swagger-demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springfox-swagger-demo Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.framework.version>4.3.6.RELEASE</spring.framework.version>
</properties> <dependencies>
<!--引入Spring依赖包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
</dependencies> <build>
<finalName>springfox-swagger-demo</finalName>
</build>
</project>

2.1.3 编写spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
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"> <!-- 默认的注解映射的支持 ,它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven /> <!-- enable autowire 向容器自动注册 -->
<context:annotation-config /> <!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.xxx.tutorial" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> </beans>

2.1.4 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" metadata-complete="true" version="3.0">
<display-name>Spring MVC</display-name>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

2.1.5 编写Controller并测试

配置好spring-mvc.xml以及web.xml文件之后,咱们继续往下走~
因为,本文Spring MVC示例的作用主要用来暴露对外HTTP API接口,先写一个简单的ProductController,其包含一个按照id查询的方法。
Product.java和ProductController.java的内容如下:
Product.java

package com.xxx.tutorial.model;

import java.io.Serializable;

/**
*
* @author wangmengjun
*
*/
public class Product implements Serializable { private static final long serialVersionUID = 1L; /**ID*/
private Long id; /**产品名称*/
private String name; /**产品型号*/
private String productClass; /**产品ID*/
private String productId; /**
* @return the id
*/
public Long getId() {
return id;
} /**
* @param id
* the id to set
*/
public void setId(Long id) {
this.id = id;
} /**
* @return the name
*/
public String getName() {
return name;
} /**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
} /**
* @return the productClass
*/
public String getProductClass() {
return productClass;
} /**
* @param productClass
* the productClass to set
*/
public void setProductClass(String productClass) {
this.productClass = productClass;
} /**
* @return the productId
*/
public String getProductId() {
return productId;
} /**
* @param productId
* the productId to set
*/
public void setProductId(String productId) {
this.productId = productId;
} /*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", productClass=" + productClass + ", productId=" + productId
+ "]";
} }

ProductController.java

package com.xxx.tutorial.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.xxx.tutorial.model.Product; @RestController
@RequestMapping(value = { "/api/product/"})
public class ProductController { @RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Product> get(@PathVariable Long id) {
Product product = new Product();
product.setName("七级滤芯净水器");
product.setId(1L);
product.setProductClass("seven_filters");
product.setProductId("T12345");
return ResponseEntity.ok(product);
}
}

注:鉴于是一个demo示例,所以没有写ProductService以及相关DAO, 直接在方法中返回固定的Product信息~

2.1.6 验证Spring MVC是否ok

完成Controller的代码,运行Spring MVC项目,然后,看一下Spring MVC是否运行ok,访问URL地址
http://localhost:8080/Springfox-swagger-demo/api/product/1

出现错误

解决方法,添加jackson-databind依赖包即可~

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.6</version>
</dependency>

重新启动,运行一下,成功返回信息~

2.2 整合SpringFox-Swagger

在SpringMVC项目中整合SpringFox-Swagger只要如下几步即可~

  • 添加SpringFox-Swagger依赖
  • 添加SwaggerConfig

添加依赖

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>

添加SwaggerConfig

package com.xxx.tutorial.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration
@EnableSwagger2
public class SwaggerConfig { @Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.build()
.apiInfo(apiInfo());
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("对外开放接口API 文档")
.description("HTTP对外开放接口")
.version("1.0.0")
.termsOfServiceUrl("http://xxx.xxx.com")
.license("LICENSE")
.licenseUrl("http://xxx.xxx.com")
.build();
} }

2.3 整合SpringFox-Swagger-UI

在SpringMVC项目中整合SpringFox-Swagger-UI也只要如下两个步骤即可~

  • 添加SpringFox-Swagger-UI依赖
  • 添加配置

 添加依赖

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>

添加配置

在添加配置之前,一起来看一下swagger-ui中使用的静态资源文件(如 swagger-ui.html )放在那里~
spingfox-swagger-ui-2.7.0.jar中的/META-INF/resources/下~ 如下图所示:

为了访问swagger-ui.html,我们配置对这些静态资源的访问~ 如:

package com.xxx.tutorial.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {   @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

该配置代码的效果和如下代码等价~

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/" />

在本文中,可以将其配置在spring-mvc.xml中,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
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"> <!-- 默认的注解映射的支持 ,它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven /> <!-- enable autowire 向容器自动注册 -->
<context:annotation-config /> <!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.xxx.tutorial" /> <bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/" />
</beans>

API接口说明代码添加并测试
经过上述几个步骤之后,之前写的ProductController的接口,就可以实现文档化了,如本文通过如下的访问地址访问:
http://localhost:8080/Springfox-swagger-demo/swagger-ui.html

这个接口API雏形出来了,但是还缺少点东西,比如:接口方法的描述等都没有~
修改一下,ProductController.java内容,如:

package com.xxx.tutorial.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.xxx.tutorial.model.Product; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; @RestController
@RequestMapping(value = { "/api/product/" })
@Api(value = "/product", tags = "Product接口")
public class ProductController { @RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(value = "根据id获取产品信息", notes = "根据id获取产品信息", httpMethod = "GET", response = Product.class)
public ResponseEntity<Product> get(@PathVariable Long id) {
Product product = new Product();
product.setName("七级滤芯净水器");
product.setId(1L);
product.setProductClass("seven_filters");
product.setProductId("T12345");
return ResponseEntity.ok(product);
}
}

重新访问,接口已经出现多个我们指定的描述信息~

在参数id栏中输入1,然后点击“try it out”按钮~ 可以查看接口调用结果~

至此一个简单的示例就完成了~

稍微增加几个接口

修改ProductController

package com.xxx.tutorial.controller;

import java.util.Arrays;
import java.util.List; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.xxx.tutorial.model.Product; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; @RestController
@RequestMapping(value = { "/api/product/" })
@Api(value = "/product", tags = "Product接口")
public class ProductController { @RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(value = "根据id获取产品信息", notes = "根据id获取产品信息", httpMethod = "GET", response = Product.class)
public ResponseEntity<Product> get(@PathVariable Long id) {
Product product = new Product();
product.setName("七级滤芯净水器");
product.setId(1L);
product.setProductClass("seven_filters");
product.setProductId("T12345");
return ResponseEntity.ok(product);
} @RequestMapping(method = RequestMethod.POST)
@ApiOperation(value = "添加一个新的产品")
@ApiResponses(value = { @ApiResponse(code = 405, message = "参数错误") })
public ResponseEntity<String> add(Product product) {
return ResponseEntity.ok("SUCCESS");
} @RequestMapping(method = RequestMethod.PUT)
@ApiOperation(value = "更新一个产品")
@ApiResponses(value = { @ApiResponse(code = 400, message = "参数错误") })
public ResponseEntity<String> update(Product product) {
return ResponseEntity.ok("SUCCESS");
} @RequestMapping(method = RequestMethod.GET)
@ApiOperation(value = "获取所有产品信息", notes = "获取所有产品信息", httpMethod = "GET", response = Product.class, responseContainer = "List")
public ResponseEntity<List<Product>> getAllProducts() {
Product product = new Product();
product.setName("七级滤芯净水器");
product.setId(1L);
product.setProductClass("seven_filters");
product.setProductId("T12345");
return ResponseEntity.ok(Arrays.asList(product, product));
}
}

swagger-ui展示

由上图可以看出,不同的method(GET / PUT / POST等)都会以不同的颜色展示出来~
Swagger-ui的添加,可以帮助他人查看接口信息,并在页面上进行输入参数来调用接口~

Maven工程的目录如下:

本文只是一个简单的整合示例,大家只要操作一下就能出来结果。
更加详细的文档,有兴趣的小伙伴可以访问swagger-ui的官网查看~

Maven+SpringMVC+SpringFox+Swagger整合示例的更多相关文章

  1. 一步步完成Maven+SpringMVC+SpringFox+Swagger整合示例

    本文给出一个整合Maven+SpringMVC+SpringFOX+Swagger的示例,并且一步步给出完成步骤. 本人在做实例时发现 http://blog.csdn.net/zth1002/art ...

  2. 关于Maven+Springmvc+Dubbo+Zookeeper整合

    为什么要用dubbo?   还是让官方来解释吧: http://dubbo.io/User+Guide-zh.htm   http://dubbo.io/   一般 nginx+tomcat  | - ...

  3. SpringMVC集成Swagger插件以及Swagger注解的简单使用

    一.简介 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新 .接口的方法,参数和模型 ...

  4. SpringMVC、SpringFox和Swagger整合项目实例

    目标 在做项目的时候,有时候需要提供其它平台(如业务平台)相关的HTTP接口,业务平台则通过开放的HTTP接口获取相关的内容,并完成自身业务~ 提供对外开放HTTP API接口,比较常用的是采用Spr ...

  5. Spring+SpringMVC+MyBatis+easyUI整合基础篇(六)maven整合SSM

    写在前面的话   承接前文<Spring+SpringMVC+MyBatis+easyUI整合基础篇(五)讲一下maven>,本篇所讲述的是如何使用maven与原ssm项目整合,使得一个普 ...

  6. Dubbo与Zookeeper、Spring整合使用 maven+springmvc+dubbo+zookeeper

    为什么要用dubbo?   还是让官方来解释吧: http://dubbo.io/User+Guide-zh.htm   http://dubbo.io/   一般 nginx+tomcat  | - ...

  7. 一篇文章带你搞懂 SpringBoot与Swagger整合

    Swagger使用由于不喜欢csdn的markwoen编辑器,对代码样式支持不好,看着不舒服,对审美要求比较高的同学移步github:https://github.com/itguang/swagge ...

  8. Zuul Swagger 整合

    疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列 [博客园总入口 ] 架构师成长+面试必备之 高并发基础书籍 [Netty Zookeeper Redis 高并发实战 ] 前言 Crazy ...

  9. Spring、SpringMVC注解方式整合

    1 原理 Web容器在启动的时候,会扫描每个jar包下的META-INF/services/javax.servlet.ServletContainerInitializer文件. 加载META-IN ...

随机推荐

  1. HTTP协议04-返回状态码

    状态码职责是在客户端向服务器端发送请求时候,描述返回的请求结果.借助状态码,用户可以知道服务器是否正常处理了请求,还是出错了. 状态码的类别   类别 原因短语 1XX Informational(信 ...

  2. python3+selenium框架设计02-自动化测试框架需要什么

    什么是自动化测试框架 自动化测试框架能够提供便利给用户高效完成一些事情,比如,结构清晰开发脚本,多种方式.平台执行脚本,良好的日志和报告去跟踪脚本执行结果. 关于自动化测试框架的定义有很多,在我大致理 ...

  3. 利用jsoncpp将json字符串转换为Vector

    在API测试过程中经常会遇到传入参数为复杂类型,一般情况下在python下,习惯用字典来表示复杂类型.但是c++对字符串的处理是比较弱智的,一般c++里边会用vector来存储复杂类型,那么就存在转换 ...

  4. Content-Type的几种常用数据编码格式

    Content-Type,内容类型,一般是指网页中存在的Content-Type,ContentType属性指定请求和响应的HTTP内容类型.如果未指定 ContentType,默认为text/htm ...

  5. Mudo C++网络库第七章学习笔记

    muduo编程示例 muduo库是设计来开发内网的网络程序, 它没有做任何安全方面的加强措施, 如果在公网上可能会受到攻击; muduo库把主动关闭连接这件事分成两步来做: 如果主动关闭连接, 会先关 ...

  6. shell 学习之if语句

    bash中如何实现条件判断?条件测试类型:    整数测试    字符测试    文件测试 一.条件测试的表达式:    [ expression ]  括号两端必须要有空格    [[ expres ...

  7. pppd[15863]: Terminating on signal 15

    由于广网于网上pptp服务器和client之间存在一些问题: 1)windows 客户端出现619 或800等错误 ----极有可能是服务器端未开启nat-t功能 2)ubunut 客户端没有拿到IP ...

  8. 大数据mapreduce二分法ip定位之Python实现

    ip定位数据大约12M,采用-chacheFile 分发 文件来源https://pan.baidu.com/s/1J0pwTafHgt4T0k3vV_gC-A 格式大致格式如下: 0.0.0.0 0 ...

  9. 3、SourceTree通过PUTTY连接GitLab

    一.生成公钥和私钥 使用命令行生成(两种生成方式选择一种即可) 1.安装SourceTree打开SourceTree,点击“命令行模式”. 2.输入如下命令生成key“example@example. ...

  10. Oracle11g 启动数据库实例、关闭数据库实例

    Oracle11g 启动数据库实例        startup 1: nomount 模式:      描述:             该模式只会创建实例(即:创建oracle 实例的各种内存结构和 ...