Swagger maven plugin 環(huán)境配置踩坑記錄

癥狀

按照該有的教程都配置完成了,swagger頁面也正常顯示,但是呢,頁面里面一個API也沒有,關(guān)鍵是我明明按照該有的步驟配置好了相關(guān)的注解了,如下圖:


api-list-empty.png

列表里面一條也木有啊。。。

Swagger環(huán)境搭建

  • 強行插入一下,不說說環(huán)境搭建你可能都對我說的東西一臉蒙蔽哈哈哈~

  • Swagger是一個很方便的合成API文檔的工具,有了它,你只要專心做API接口就行了,接口文檔Swagger幫你完成,畢竟寫完代碼之后一想到還要給App或者H5團隊一個個講自己的接口該怎么用,實在是很心累,有了Swagger,只要你的接口開發(fā)完畢,部署到測試服務器,只要把swagger頁面鏈接扔給他們就行了~ 多爽~

我這里使用maven的插件方式在項目中接入Swagger,項目使用SpringMVC
  1. maven依賴,列出swagger使用的相關(guān)依賴,其他Spring和SpringMVC的自己添加:
        <!-- AOP合成字節(jié)碼的實現(xiàn)框架 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.3</version>
            <scope>runtime</scope>
        </dependency>
        <!-- Spring AOP模塊 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>
        <!-- JSON處理框架 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.4</version>
        </dependency>
        <!-- Swagger依賴 -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-core</artifactId>
            <scope>compile</scope>
            <version>1.5.3</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.ws.rs</groupId>
                    <artifactId>jsr311-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
  1. 然后是maven插件配置,順便把jetty和打包插件也列出
    <build>
        <finalName>doc-searcher-web</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <!-- jetty插件 -->
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.20</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8080</port>
                            <maxIdleTime>60000</maxIdleTime>
                        </connector>
                    </connectors>
                    <contextPath>/doc-searcher-web</contextPath>
                    <systemProperties>
                        <systemProperty>
                            <name>org.mortbay.jetty.Request.maxFormContentSize</name>
                            <value>-1</value>
                        </systemProperty>
                    </systemProperties>
                </configuration>
            </plugin>
            <!-- maven編譯插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- maven資源插件,作用于maven的resources目錄下 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- maven war包打包插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <warName>${project.artifactId}</warName>
                </configuration>
            </plugin>
            <!-- 重點:swagger插件 -->
            <plugin>
                <groupId>com.github.kongchen</groupId>
                <artifactId>swagger-maven-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <apiSources>
                        <apiSource>
                            <!-- 支持springMVC -->
                            <springmvc>true</springmvc>
                           <!-- 你的web項目Controller包名 --> <locations>cn.coselding.docsearcher.web.controller</locations>
                           <!-- 協(xié)議 -->
                            <schemes>http</schemes>
                            <!-- 所在主機,可以為空 -->
                            <host>localhost:8080</host>
                            <!-- web項目Context Path -->
                            <basePath>/doc-searcher-web</basePath>
                            <!-- 必須!要在主頁顯示你的API的整體信息的,相當于是標題 -->
                            <info>
                                <title>文檔搜索器</title>
                                <version>v1</version>
                                <description>
                                    文檔搜索器-API
                                </description>
                            </info>
                           <!-- 模板位置,支持classpath:類型路徑 --> <templatePath>classpath:/template/markdown.hbs</templatePath>
                           <!-- 編譯期掃描controller之后合成的API文檔輸出位置 --> <outputPath>${project.basedir}/src/main/webapp/swagger-ui/document.md</outputPath>
                           <!-- web目錄下的js、css等資源位置 --> <swaggerDirectory>${project.basedir}/src/main/webapp/swagger-ui/</swaggerDirectory>
                        </apiSource>
                    </apiSources>
                </configuration>
                <!-- 這里很重要,簡單說就是配置在maven的compile生命周期執(zhí)行時觸發(fā)swagger插件的generate命令 -->
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

很好理解,在maven的compile生命周期觸發(fā)的時候觸發(fā)swagger的generate命令,當然你直接使用插件的generate手動執(zhí)行也可以,執(zhí)行完成之后會在webapp/swagger-ui/目錄下生成swagger.json里面就列出了掃描到的所有接口信息。

  1. webapp目錄下放入資源文件,是一些css、js、html之類的文件,如下圖:


    webapp-resources.png
  2. classpath下放入一些模板資源文件,如下圖:


    classpath-resources.png

    以上這兩個資源包是公司一個大佬@張章改過的,網(wǎng)上沒找到,最后會給出幾個博客,也能拿到相關(guān)的資源,不過是官方原生的。

  3. SpringMVC配置

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

    <!-- Controller包掃描 -->
    <context:component-scan base-package="cn.coselding.docsearcher.web.controller"/>

    <!-- springMVC注解驅(qū)動支持 -->
    <mvc:annotation-driven/>

    <!-- 容器默認的DefaultServletHandler處理 所有靜態(tài)內(nèi)容與無RequestMapping處理的URL,不設(shè)置這個你在請求剛才的js、css文件就請求不到了 -->
    <mvc:default-servlet-handler/>

    <!-- 聲明swagger資源文件位置,表示這個路徑下的SpringMVC的DispatcherServlet不攔截 -->
    <mvc:resources mapping="/swagger-ui/**" location="/swagger-ui/"/>
    <!-- SpringMVC設(shè)置AOP -->
    <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="false"/>
</beans>

這里主要就是配置這個AOP,它會在編譯期攔截讀取各個Controller的注解接口信息,提取關(guān)鍵數(shù)據(jù),合成swagger.json文件,有了這個文件,剩下那些html就能渲染出相關(guān)的接口文檔頁面。

  1. 上面那些是整體環(huán)境配置,接下來只要在Controller編寫的時候加點注解,文檔就幫你合成好啦~
    注解使用:如下一個樣例Controller:
/**
 * @author linyuqiang
 * @version 1.0.0 2017/4/4
 */
@Controller
@RequestMapping("/test")
@Api("文檔搜索器API")
public class UrlCatcherController {

    @ApiOperation("測試1")
    @RequestMapping(value = "/spider/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Map spider(
            @ApiParam(required = true,name = "id",value = "測試id")
            @PathVariable("id") Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("result", "success");
        result.put("id", id);
        return result;
    }
}
  • @Api("文檔搜索器API"):這個是整個Controller的標題,Controller下的所有接口會被整理在同一個列表組下,組名組名就是這個。
  • @ApiOperation("測試1"):這個是具體的一個接口的名稱
  • @ApiParam(required = true,name = "id",value = "測試id"):這個是接口參數(shù)的標注,required不用說,name標注作用的表單參數(shù)名稱,和下面的id對應,value是文檔頁面上這個參數(shù)的描述
之后,maven jetty啟動項目,訪問頁面http://localhost:8080/doc-searcher-web/swagger-ui/index.html,如下圖所示:
swagger-show.png

還能在參數(shù)那邊輸入對應的值,直接測試接口呢~

踩坑記錄

  1. 如果你設(shè)置了SpringMVC攔截器,要注意,必須對webapp/swagger-ui/目錄下的exclude,不然會報錯~如下:
    <mvc:interceptors>
        <!-- Jobs鑒權(quán)攔截器 -->
        <mvc:interceptor>
            <mvc:mapping path="/**/*"/>
            <!-- 排除對swagger-ui目錄下的攔截 -->
            <mvc:exclude-mapping path="/swagger-ui/**"/>
            <bean class="com.weidian.jobs.web.interceptor.JobsAuthInterceptor">
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>
  1. 文首,我的Swagger頁面居然沒有API列表是為什么?如下是我之前的Controller方法注解:
    @ApiOperation("測試1")
    @RequestMapping(value = "/spider/{id}")
    @ResponseBody
    public Map spider(
            @ApiParam(required = true,name = "id",value = "測試id")
            @PathVariable("id") Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("result", "success");
        result.put("id", id);
        return result;
    }

對,就是沒method = RequestMethod.POST參數(shù),你這邊寫了什么參數(shù),Swagger就給你在API列表相應添加一條,沒寫就什么都沒有,這個錯誤我犯了兩次了,真不能忍?。。。?/p>

相關(guān)博客

末尾,來幾個搭建教程,里面就有相關(guān)的swagger資源包的下載地址啦~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容