最近使用swagger自動生成api文檔遇到了不少坑,網上有許多教程,但都并不能順利運作。現自己整理了一份,以備之後用到時使用。
在這之前需要注意的幾個問題:
1.jar包是否引用完整;
2.是否下載下傳了比對版本的swagger-ui(該案例中使用了swagger-ui 2.2.10版本),jar包中swagger-springmvc版本為1.0.2。該問題若不注意可能引起以下問題:
No operations defined in spec!
3.applicationContext.xml配置檔案中請按照以下順序填寫,否則可能引起掃描注入失敗的報錯.
<context:component-scan base-package="com.controller" />
<!-- 自定義的SwaggerConfig類 -->
<bean class="com.swagger.config.SwaggerConfig" />
4.spring-mvc.xml中必須配置以下兩項
<!-- 啟用注解掃描 -->
<mvc:annotation-driven />
<!-- 靜态資源所在路徑過濾 允許資源通路 -->
<mvc:resources location="/swagger-tempate/" mapping="/swagger-tempate/**" />
5.修改swagger-ui中的dist目錄下index.html中讀取url配置的路徑為:目前部署路徑+ 項目名+“/api-docs”
url = "http://localhost:5508/api-docs";
由于我的項目名設定為"/",是以這裡直接忽略
附上運作結果圖:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVPZRUTzEkaNNTW61kZWhkWwZUbZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DO0gjNzADNwIDNxETM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
以下附上按照盡可能簡單的最小依賴的寫法:
1.配置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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.swagger</groupId>
<artifactId>swagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>swagger自動生成api文檔</name>
<description>swagger與spring mvc結合自動生成api文檔</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.4.RELEASE</spring.version>
<jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</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-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>swagger</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<!-- <verbose /> -->
<extdirs>${project.basedir}\src\main\webapp\WEB-INF\lib</extdirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>webapp</directory>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<configuration>
<webAppSourceDirectory>webapp</webAppSourceDirectory>
<webAppConfig>
<allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>
</webAppConfig>
<webApp>
<contextPath>/</contextPath>
</webApp>
<stopKey>webx</stopKey>
<stopPort>9998</stopPort>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>5508</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<requestLog implementation="org.eclipse.jetty.server.NCSARequestLog">
<filename>target/access.log</filename>
<retainDays>90</retainDays>
<append>false</append>
<extended>false</extended>
<logTimeZone>GMT+8:00</logTimeZone>
</requestLog>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.配置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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>swagger</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringMVC</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>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.配置applicationContext.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">
<context:component-scan base-package="com.controller" />
<bean class="com.swagger.config.SwaggerConfig" />
</beans>
4.配置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: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 />
<mvc:resources location="/swagger-tempate/" mapping="/swagger-tempate/**" />
</beans>
5.Controller核心代碼
package com.controller;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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.swagger.vo.User;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/Test")
public class TestController {
/*其中@ApiOperation和@ApiParam為添加的API相關注解,個參數說明如下:
*
@ApiOperation(value = "接口說明", httpMethod = "接口請求方式", response = "接口傳回參數類型", notes = "接口釋出說明")
@ApiParam(required = "是否必須參數", name = "參數名稱", value = "參數具體描述")
produces = "text/plain;charset=utf-8" 設定傳入接收字元編碼為utf-8
*/
@RequestMapping(value = "/demo_get", method = RequestMethod.GET, produces = "text/plain;charset=utf-8" )
@ApiOperation(value = "GET請求", httpMethod = "GET", notes = "get請求案例")
public @ResponseBody String demo_get(
@ApiParam(required = true, name = "name", value = "使用者名")
@RequestParam(required=false) String name){
return "你輸入的名字:"+name;
}
@RequestMapping(value = "/demo_post", method = RequestMethod.POST, produces = "text/plain;charset=utf-8" )
@ApiOperation(value = "POST請求 鍵值對參數送出", httpMethod = "POST", notes = "post請求案例, 參數以鍵值對方式送出, 傳回一個json對象", response = User.class)
public @ResponseBody String demo_post(
@ApiParam(required = true, name = "name", value = "使用者名")
@RequestParam(required=false) String name){
User user = new User();
user.setId(String.valueOf(new Date().getTime()));
user.setName(name);
user.setAge(22);
user.setCompany("人生有限公司");
user.setGender(1);
user.setIc("12345678910");
user.setPhone("400800888");
user.setSchool("北大還行");
JSONObject object = JSONObject.fromObject(user);
return object.toString();
}
@RequestMapping(value = "/demo_post2", method = RequestMethod.POST, produces = "application/json;charset=utf-8" )
@ApiOperation(value = "POST請求 json格式參數送出", httpMethod = "POST", notes = "post請求案例, json格式參數送出, 傳回一個json對象")
public @ResponseBody String demo_post2(
@ApiParam(required = true, name = "user", value = "使用者對象json格式參數")
@RequestBody User user){
JSONObject object = JSONObject.fromObject(user);
JSONObject result = new JSONObject();
result.put("result", 1);
result.put("object", object);
return result.toString();
}
}
附上親測代碼demo:
http://download.csdn.net/download/baidu_36720706/10118720
由于該demo已經內建jetty,請直接使用jetty執行項目
eclipse環境中運作jetty步驟如下:
另外附上兩個看了幫助較大的文章連結:
http://blog.csdn.net/u011499992/article/details/53455144
java注解方式,非xml配置檔案實作:
http://blog.csdn.net/gyb_csdn/article/details/75123575