SpringMVC+Swagger UI生成可视图的API文档(详细图解)

简介:

SpringMVC+Swagger UI生成可视图的API文档(详细图解)http://www.bieryun.com/1106.html

Swagger UI

关于Swagger UI官方解释是这样的:The Swagger UI is an open source project to visually render documentation for a Swagger defined API directly from the API’s Swagger specifcation 官网地址
下面是官方的效果图:
文档效果图
我将上图分成了两部分

  1. 文档地址:从改地址请求数据,获取JSON格式数据,交给第二步显示
  2. API文档显示:将JSON数据转化成可视图的效果

Swagger可以将某种固定格式的JSON数据生成可以视图的在线API文档,支持在线测试,可以清楚的观察到IO数据。

SpringMVC + Swagger

目的:在原有的SpringMVC系统中添加Swagger,通过在接口上添加注解实现,接口文档的同步效果。
下图为我实现之后的效果:
简易效果

项目搭建

我的工具:Eclipse开发工具(安装Spring插件,当然也可以不要,就是麻烦点),Maven,Tomcat,Internet访问,Chrome浏览器
1.创建Simple Spring Web Maven工程
右键New->Spring Project,选择对应类型,finish, 如下图:Simple Spring Web Maven Project
我的工程的结构,注意那两个配置文件,名称不重要,可以随便改,注意要对应好web.xml中的名称就行。项目结构
想了想还是把三个配置文件贴出来吧。
web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<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_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>SwaggerDemo</display-name>

   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

application-config.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Uncomment and add your base-package here:
         <context:component-scan
            base-package="org.springframework.samples.service"/>  -->

</beans>

mvc-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Uncomment and your base-package here:
         <context:component-scan
            base-package="org.springframework.samples.web"/>  -->


    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>

这样配置到后面配置Swagger会出现无法自动注入的问题,后面再说,以上为工具自动生成的代码。

2.添加Swagger-Spring MVC包、JSON和jackson
pom.xml文件中
properties标签里面添加jackson版本号

<version.jackson>2.4.4</version.jackson>

dependencies标签中添加

    <!-- Swagger -->
    <dependency>
        <groupId>com.mangofactory</groupId>
        <artifactId>swagger-springmvc</artifactId>
        <version>0.9.5</version>
    </dependency>
    <!-- JSON -->
    <dependency>  
        <groupId>net.sf.json-lib</groupId>  
        <artifactId>json-lib</artifactId>  
        <version>2.4</version>  
        <classifier>jdk15</classifier>   
    </dependency>   
    <!-- JACKSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${version.jackson}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${version.jackson}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${version.jackson}</version>
    </dependency>

3.下面是重点,Swagger所有API文档都在这里存储,添加Swagger配置类
创建一个配置类MySwaggerConfig,添加私有成员SpringSwaggerConfig,set方法使用@Autowired注解自动注入,使用@Bean注解添加SwaggerSpringMvcPlugin,并使用自定义的ApiInfo,SwaggerConfig类需要添加@Configuration以及@EnableSwagger

package com.edu.xk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;

@Configuration
@EnableSwagger
@EnableWebMvc
public class MySwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    /**
     * Required to autowire SpringSwaggerConfig
     */
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
     * framework - allowing for multiple swagger groups i.e. same code base
     * multiple swagger resource listings.
     */
    @Bean
    public SwaggerSpringMvcPlugin customImplementation() {
        // 暂时不用过滤
        /*return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(".*pet.*");*/
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                  "My Apps API Title",
                  "My Apps API Description",
                  "My Apps API terms of service",
                  "My Apps API Contact Email",
                  "My Apps API Licence Type",
                  "My Apps API License URL"
            );
        return apiInfo;
    }
}

官方原话:
The @EnableSwagger annotation, in this example, enables swagger-springmvc out of the box. The generated swagger json Resource Listing is available at /api-docs
4.添加Controller:WebServiceForCSS,Swagger文档在此处添加

package com.edu.xk.webservice;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.edu.xk.model.User;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

import net.sf.json.JSONObject;

/**
 * @moudle: WebServiceForCSS
 * @version:v1.0
 * @Description: TODO
 * @author: xukai
 * @date: 2016年12月1日 下午5:37:30
 *
 */
@Controller
public class WebServiceForCSS {

    @ResponseBody
    @RequestMapping(value = "getUserById", method = RequestMethod.GET, produces = {"application/json; charset=utf-8","application/xml"})
    @ApiOperation(value = "通过ID查询USER信息", httpMethod = "GET", notes = "暂无")
    public String getUserById(
            @ApiParam(required = true, name = "id", value = "ID") 
            @RequestParam(value = "id") String id,HttpServletRequest request) {
        User user = new User();
        user.setId(id);
        user.setName("测试人员");
        user.setAge(25);
        JSONObject object = JSONObject.fromObject(user);
        return object.toString();
    }
}

5.配置文件修改
context加载的时候需要配置的文件,此处配置文件为application-config.xml

        <mvc:annotation-driven /> <!-- mvc-config.xml中的可以去掉 -->
        <context:component-scan base-package="com.edu"/>
        <bean class="com.edu.xk.configer.SwaggerConfig"/>

6.下载Swagger UI组件
去官网下载Zip包,或者在github上下载也可以,需要将dist文件夹下的所有文件的复制到webapp目录下。

7.修改Project Properties
将jdk1.5换成最新的本地的jdk,对应的Java complier也改为对应的,还有maven包依赖也需要添加,不然启动的时候会找不到ContextLoader.class。

8.添加拦截器,不然无法访问.html后缀文件,在web.xml中添加

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.gif</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.ico</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.xls</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.doc</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
    <!-- 字体相关  开始 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.eot</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.svg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.ttf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.woff</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.woff2</url-pattern>
    </servlet-mapping>
    <!-- 字体相关  结束 -->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

运行项目,可以看到效果图:
官方图
可以看到,现在效果还是和官网上一样的。改为自己的API文档可以通过修改index.html中的url = "http://petstore.swagger.io/v2/swagger.json";或者直接修改访问的地址栏为:http://localhost:8080/SwaggerDemo/api-docs

原理分析

SpringMVC+Swagger其实就是在系统加载的时候,Swagger配置类去扫描所有添加注释的接口,并且储存起来通过下面地址进行访问,返回JSON数据,在前端界面显示出来
访问路径
这里我在网上看到一个汉化的版本(原效果),下载了他工程,将他生成demo.json放入的我的工程中的webapp目录下,下面是效果图
官网API转为中文

遇到的问题

  • 问题1:下载maven的jar包中途失败,工程会出错maven missing
    解决方法:选中Project->右键maven->update project->选中Force update 如果此时依然有
    missing的jar,按照 buildpath 提示的 jar包missing 路径,去 maven
    本地仓库中对应位置(jar包后面有路径),删掉 该 jar 包的 xxx.lastUpdated 文件,之后,再重新执行
    项目右键maven->update project
  • 问题2:缺失jackson包会导致出现异常java.lang.NoClassDefFoundError:
    com/fasterxml/jackson/databind/ObjectMapper)
  • 问题3:java.lang.ClassNotFoundException:
    org.springframework.web.util.Log4jConfigListen,因为工程没有引入maven中的jar包,解决办法:选中工程右键->Properties->Deployment Assembly->add->Java Build Path Entries->Maven Dependencies->OK
  • 问题4:org.springframework.beans.factory.BeanCreationException,出现这个异常是因为SpringSwaggerConfig的私有成员RequestMappingHandlerMapping造成的,将<mvc:annotation-driven />放入到web.xml的context-param标签对应的配置文件application-config.xml中,完美解决,官网解释该标签作用为: Required so swagger-springmvc can access spring’s RequestMappingHandlerMapping 。
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No
    qualifying bean of type
    [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]
    found for dependency [collection of
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]:
    expected at least 1 bean which qualifies as autowire candidate for
    this dependency. Dependency annotations:
    {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    Swagger UI开发帮助

Swagger Editor

反正顺路,顺便的Editor也写完,Editor个人感觉就是一个文档编辑器,感觉SosoApi还是好些。试着在Swagger官网下载了一个Swagger Editor跑着玩了玩.下载swagger-editor.zip,解压到Tomcat的webapps文件夹中,来看一下效果图
本地Editor
Swagger UI结合Swagger Editor更好用,但是在线编辑那个太卡了,备份一个本地的,以备不时只需。

相关文章
|
人工智能 安全 架构师
告别旅行规划的"需求文档地狱"!这个AI提示词库,让你像调API一样定制完美旅程
作为开发者,旅行规划如同“需求地狱”:信息碎片、需求多变、缺乏测试。本文提出一套“企业级”AI提示词库,将模糊需求转化为结构化“API请求”,实现标准化输入输出,让AI成为你的专属旅行架构师,30分钟生成专业定制方案,提升决策质量,降低90%时间成本。
1172 129
|
JSON API 数据格式
小红书API接口文档:笔记详情数据开发手册
小红书笔记详情API可获取指定笔记的标题、正文、互动数据及多媒体资源,支持字段筛选与评论加载。通过note_id和access_token发起GET/POST请求,配合签名验证,广泛用于内容分析与营销优化。
2393 3
阿里云短信服务文档与实际API不符
阿里云短信服务文档与实际API不符
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
XML JSON API
如何从 Swagger 导出 API 文档
Swagger 使这项任务相对简单,允许开发者以各种格式(如 JSON 和 YAML)导出 API 文档。在这篇博文中,我们将详细探讨如何从 Swagger 导出 API 文档。
如何从 Swagger 导出 API 文档
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
487 14
|
API 开发者
通义灵码 API 开发文档自动生成场景DEMO
通义灵码API开发文档自动生成场景DEMO展示了通过自定义指令,大模型能快速根据类代码生成Markdown格式的API文档。文档详细描述API的入参、出参,并可生成测试代码等示例,帮助开发者快速创建美观的API文档。
998 1
|
Java 测试技术 API
详解Swagger:Spring Boot中的API文档生成与测试工具
详解Swagger:Spring Boot中的API文档生成与测试工具
1534 4
|
JSON 前端开发 API
后端开发中的API设计与文档编写指南####
本文探讨了后端开发中API设计的重要性,并详细阐述了如何编写高效、可维护的API接口。通过实际案例分析,文章强调了清晰的API设计对于前后端分离项目的关键作用,以及良好的文档习惯如何促进团队协作和提升开发效率。 ####
|
Java API 数据中心
百炼平台Java 集成API上传文档到数据中心并添加索引
本文主要演示阿里云百炼产品,如何通过API实现数据中心文档的上传和索引的添加。
1884 4