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

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 官网地址
下面是官方的效果图:
SpringMVC+Swagger UI生成可视图的API文档(详细图解)_第1张图片
我将上图分成了两部分

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

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

SpringMVC + Swagger

目的:在原有的SpringMVC系统中添加Swagger,通过在接口上添加注解实现,接口文档的同步效果。
下图为我实现之后的效果:
SpringMVC+Swagger UI生成可视图的API文档(详细图解)_第2张图片

项目搭建

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


<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>SwaggerDemodisplay-name>

   
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring/application-config.xmlparam-value>
    context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>


    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/mvc-config.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

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

web-app>

application-config.xml



<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">

    

beans>

mvc-config.xml



<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">

    


    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            
            <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.4version.jackson>

dependencies标签中添加

    
    <dependency>
        <groupId>com.mangofactorygroupId>
        <artifactId>swagger-springmvcartifactId>
        <version>0.9.5version>
    dependency>
    
    <dependency>  
        <groupId>net.sf.json-libgroupId>  
        <artifactId>json-libartifactId>  
        <version>2.4version>  
        <classifier>jdk15classifier>   
    dependency>   
    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>${version.jackson}version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>${version.jackson}version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <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 /> 
        <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>defaultservlet-name>
        <url-pattern>*.jpgurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.pngurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.gifurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.icourl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.jsurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.cssurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.htmlurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.xlsurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.docurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.jsonurl-pattern>
    servlet-mapping>
    
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.eoturl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.svgurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.ttfurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.woffurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.woff2url-pattern>
    servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>

运行项目,可以看到效果图:
SpringMVC+Swagger UI生成可视图的API文档(详细图解)_第5张图片
可以看到,现在效果还是和官网上一样的。改为自己的API文档可以通过修改index.html中的url = "http://petstore.swagger.io/v2/swagger.json";或者直接修改访问的地址栏为:http://localhost:8080/SwaggerDemo/api-docs

原理分析

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

遇到的问题

  • 问题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造成的,将放入到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文件夹中,来看一下效果图
SpringMVC+Swagger UI生成可视图的API文档(详细图解)_第8张图片
Swagger UI结合Swagger Editor更好用,但是在线编辑那个太卡了,备份一个本地的,以备不时只需。

相关下载

官方swagger-ui-master.zip:解压可得上文所说dist中所有文件
SwaggerDemo.zip:上文中的DEMO

你可能感兴趣的:(java)