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

癥狀

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


api-list-empty.png

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

Swagger環(huán)境搭建

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

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

我這里使用maven的插件方式在項(xiàng)目中接入Swagger,項(xiàng)目使用SpringMVC
  1. maven依賴,列出swagger使用的相關(guān)依賴,其他Spring和SpringMVC的自己添加:
        <!-- AOP合成字節(jié)碼的實(shí)現(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>
            <!-- 重點(diǎn):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項(xiàng)目Controller包名 --> <locations>cn.coselding.docsearcher.web.controller</locations>
                           <!-- 協(xié)議 -->
                            <schemes>http</schemes>
                            <!-- 所在主機(jī),可以為空 -->
                            <host>localhost:8080</host>
                            <!-- web項(xiàng)目Context Path -->
                            <basePath>/doc-searcher-web</basePath>
                            <!-- 必須!要在主頁(yè)顯示你的API的整體信息的,相當(dāng)于是標(biāo)題 -->
                            <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>
                <!-- 這里很重要,簡(jiǎn)單說就是配置在maven的compile生命周期執(zhí)行時(shí)觸發(fā)swagger插件的generate命令 -->
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

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

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


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


    classpath-resources.png

    以上這兩個(gè)資源包是公司一個(gè)大佬@張章改過的,網(wǎng)上沒找到,最后會(huì)給出幾個(gè)博客,也能拿到相關(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ū)動(dòng)支持 -->
    <mvc:annotation-driven/>

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

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

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

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

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

還能在參數(shù)那邊輸入對(duì)應(yīng)的值,直接測(cè)試接口呢~

踩坑記錄

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

對(duì),就是沒method = RequestMethod.POST參數(shù),你這邊寫了什么參數(shù),Swagger就給你在API列表相應(yīng)添加一條,沒寫就什么都沒有,這個(gè)錯(cuò)誤我犯了兩次了,真不能忍啊?。?!

相關(guān)博客

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

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

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

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