swagger与springMVC、maven整合

最近使用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";
由于我的项目名设置为"/",因此这里直接忽略

附上运行结果图:




以下附上按照尽可能简单的最小依赖的写法:

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

猜你喜欢

转载自blog.csdn.net/baidu_36720706/article/details/78534606
今日推荐