最近主要负责接口开发,每次都用以前用过的postman,发现配置参数这些比较麻烦,然后有人推荐用swagger。于是尝试将swagger整合到项目中。
配置
//pomx.xml 添加依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.7version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.10version>
dependency>
<dependency>
<groupId>commons-httpclientgroupId>
<artifactId>commons-httpclientartifactId>
<version>3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.2version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.32version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
<type>jartype>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.mangofactorygroupId>
<artifactId>swagger-springmvcartifactId>
<version>1.0.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.7.0version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.6.1version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.8.9version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.8.9version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.8.9version>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>22.0version>
dependency>
dependencies>
如果项目中想要使用注解@ApiImplicitParam。则一定要配置com.google.guava.不然后会抛出异常。
//springmvc spring-servlet.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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.ezparking">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView">property>
<property name="prefix" value="/WEB-INF/views/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
bean>
mvc:message-converters>
mvc:annotation-driven>
<mvc:resources location="/static/" mapping="/static/**"/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
beans>
//spring applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.ezparking" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<mvc:annotation-driven />
beans>
这里配置也是最简单配置。本项目主要在于整合swagger.
//在代码中引入swagger配置类。这个配置类就等于构建了一个MVC的接口容器Docket。这个容器可以配置管理哪些接口
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@EnableWebMvc
@Configuration
public class ApplicationSwaggerConfig extends WebMvcConfigurationSupport {
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select() /*注册回调*/
.apis(RequestHandlerSelectors.basePackage("com.ezparking.controller"))/*配置API的基本包路径。一般接口都配置在controller包里。当然可以根据自己要求配置*/
.paths(PathSelectors.any())/*接口的路径配置。any就是可以是任意路径*/
.build();
}
/*接口文档的一些基本信息可以自己根据具体配置*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("restulful API")
.termsOfServiceUrl("www.baidu.com")
.contact(new Contact("ezparking", "", ""))
.version("1.0.0")
.build();
}
}
@Controller
@RequestMapping("/")
@Api(description="大数据接口")
public class DashboardController {
/**
* RTPI数据统计
*paramType path 用于restfule rtpi/{id}/{age} query 参数添加在url后面
*consumes="application/x-www-form-urlencoded" 配置请求在数跟在url后面保证可以映射到对应的参数
* @return RTPI数据统计信息
*/
@RequestMapping(value="/rtpi",produces = "application/json; charset=utf-8")
@ResponseBody
@ApiOperation(value="获取数据", httpMethod="POST",consumes="application/x-www-form-urlencoded", notes="根据停车场获取数据")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户姓名", required = false, dataType = "String",paramType="query"),
@ApiImplicitParam(name = "age", value = "用户年龄", required = false, dataType = "String",paramType="query"),
@ApiImplicitParam(name = "parking", value = "停车场", required = false, dataType = "Parking")
})
public String rtpiData( String id, String age,Parking parking) {
System.out.println(id + age+parking.getAddress()+parking.getName());
return HttpUtils.doGet(propertiesUtils.getProperty("rtpi"));
}
}
在一个controller中添加API的注解。然后部署项目。启动。访问路径http://localhost:8080/rtpi-dashboard/swagger-ui.html
得到如下页面
点击任意接口
到这里基本整合完毕。下面是一些常用的注解参数的文档整理。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Api {
//url路径值
String value() default "";
//如果设置这个值、value的值会被覆盖
String[] tags() default "";
//接口的描述。已过时。但是我没发现用什么注解来代替。
@Deprecated String description() default "";
//如果有多个接口类集合,可以决定该接口类的位置
@Deprecated int position() default 0;
//"application/json, application/xml" 指定返回的内容类型
String produces() default "";
//"application/json, application/xml" 指定处理的请求类型
String consumes() default "";
//支持哪些协议。如:http, https, ws, wss多个协议用逗号分隔
String protocols() default "";
//权限配置
Authorization[] authorizations() default @Authorization(value = "");
//是否隐藏。
boolean hidden() default false;
}
//描述方法用途
String value();
//详细描述
String notes() default "";
//如果配置将会覆盖value
String[] tags() default "";
//返回的对象
Class> response() default Void.class;
//返回可以包含的集合 "List", "Set" or "Map". 其它都会被忽略
String responseContainer() default "";
//返回的对象引用。注解次值将会覆盖response
String responseReference() default "";
//接口方法类型。"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH".
String httpMethod() default "";
//接口的位置
@Deprecated int position() default 0;
//别名?不知道有啥用目前
String nickname() default "";
//响应的类型 "application/json, application/xml"
String produces() default "";
//请求的类型。"application/json, application/xml"
String consumes() default "";
//协议
String protocols() default "";
//权限配置
Authorization[] authorizations() default @Authorization(value = "");
//是否隐藏
boolean hidden() default false;
//响应头
ResponseHeader[] responseHeaders() default @ResponseHeader(name = "", response = Void.class);
//响应编码
int code() default 200;
//扩展
Extension[] extensions() default @Extension(properties = @ExtensionProperty(name = "", value = ""));
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户姓名", required = false, dataType = "String",paramType="path"),
@ApiImplicitParam(name = "age", value = "用户年龄", required = false, dataType = "String",paramType="path"),
@ApiImplicitParam(name = "parking", value = "停车场", required = false, dataType = "Parking")
//参数名称
String name() default "";
//默认值
String defaultValue() default "";
//设置参数范围
String allowableValues() default "";
//是否必须
boolean required() default false;
//过滤某个参数
String access() default "";
//允许某个参数多个值
boolean allowMultiple() default false;
//参数类型
String dataType() default "";
//参数类型。配置这个会覆盖dataType
Class> dataTypeClass() default Void.class;
//参数路径类型。path,query,body,header,form.这个参数比较重要。如果path,说明该参数应该是restful风格。对应的参数应该用@PathVariable修饰。 如果参数是其它类型,那么在@ApiOperation 中应该指定consumes="application/x-www-form-urlencoded"。否则默认的是json格式将无法映射到具体的参数。
String paramType() default "";
String example() default "";
Example examples() default @Example(value = @ExampleProperty(mediaType = "", value = ""));
String type() default "";
String format() default "";
//允许为空
boolean allowEmptyValue() default false;
//只读
boolean readOnly() default false;
String collectionFormat() default "";
没写注释的说明目前还没用到,也还没真正弄明白啥意思。希望随着用的熟悉能越来越多的理解更多的参数。了解上面的参数基本已经能够配置常用的接口管理。