1. Swagger概述
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
作用:
1. 接口的文档在线自动生成,方便管理项目中API接口。
2. 方便前后端联合开发,以及三方调用。
3. 方便接口测试。
以下是我们项目中swagger+springmvc的配置使用步骤,文中示例代码仅供使用参考,不能直接运行。
2. swagger + springmvc配置使用步骤
一、在pom.xml中引入maven依赖。
<!-- springfox start -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.6</version>
</dependency>
<!-- springfox end -->
二、添加自定义SwaggerConfig.java类文件,文件内容如下:
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket userAPI() {
ApiInfo apiInfo = new ApiInfo(
"接口文档",
"XX项目的接口文档,此文档包含user级别的所有接口说明。",
"",
"",
new Contact("davidpeng", "", "[email protected]"),
"",
""
);
Set<String> setProtocol = new HashSet<String>();
setProtocol.add("http");
Set<String> setProduce = new HashSet<String>();
setProduce.add("application/json");
Set<String> setConsume = new HashSet<String>();
setConsume.add("x-www-form-urlencoded");
List<Parameter> listParameter = new ArrayList<Parameter>();
listParameter.add(
new ParameterBuilder()
.name("X-Toon-User-ID")
.description("User ID")
.parameterType("header")
.required(true)
.modelRef(new ModelRef("string"))
.build()
);
listParameter.add(
new ParameterBuilder()
.name("X-Toon-User-Token")
.description("User Token")
.parameterType("header")
.required(true)
.modelRef(new ModelRef("string"))
.build()
);
listParameter.add(
new ParameterBuilder()
.name("X-Toon-User-Agent")
.description("User Agent")
.parameterType("header")
.required(true)
.modelRef(new ModelRef("string"))
.build()
);
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.regex("/user/.*"))
.build()
.groupName("User")
.pathMapping("/")
.enable(true)
.apiInfo(apiInfo)
.useDefaultResponseMessages(false)
.globalOperationParameters(listParameter)
.protocols(setProtocol)
.produces(setProduce)
.consumes(setConsume);
}
@Bean
public Docket openAPI() {
ApiInfo apiInfo = new ApiInfo(
"接口文档",
"XX项目的接口文档,此文档包括open级别的所有接口说明",
"",
"",
new Contact("davidpeng", "", "[email protected]"),
"",
""
);
Set<String> setProtocol = new HashSet<String>();
setProtocol.add("http");
Set<String> setProduce = new HashSet<String>();
setProduce.add("application/json");
Set<String> setConsume = new HashSet<String>();
setConsume.add("x-www-form-urlencoded");
List<Parameter> listParameter = new ArrayList<Parameter>();
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.regex("/open/.*"))
.build()
.groupName("Open")
.pathMapping("/open")
.enable(true)
.apiInfo(apiInfo)
.useDefaultResponseMessages(false)
.globalOperationParameters(listParameter)
.protocols(setProtocol)
.produces(setProduce)
.consumes(setConsume);
}
@Bean
public UiConfiguration uiConfig() {
return new UiConfiguration(
"validatorUrl",// url
"none", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
true, // enableJsonEditor => true | false
true); // showRequestHeaders => true | false
}
}
注:其中ApiInfo构造参数需要做相应修改,其它参数可以使用文件中配置好的,各参数和注解含义在此不做说明,如需了解请自己查看官方文档。
三、将上一步中SwaggerConfig配置加入Spring容器中(dispatcher-servlet.xml),如下:
<!-- springfox配置 -->
<bean class="com.XXXX.api.swagger.SwaggerConfig" />
四、为了访问swagger-ui.html等静态资源,需在dispatcher-servlet.xml中加入如下配置:
<!-- 静态资源访问 -->
<!--<mvc:default-servlet-handler />-->
<mvc:resources mapping="/**" location="/"/>
五、由于当前API项目中包含不同级别的API接口,所以配置不同的拦截器用以处理不同级别接口相关验证,在dispatcher-servlet.xml中加入如下配置:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/*"/>
<bean id="baseRequestInterceptor" class="com.XXX.commons.api.user.XXXRequestInterceptor">
<property name="ignoreVerifyList">
<list>
<value>addRecommendation</value>
<value>checkRecommendStatus</value>
<value>createCustomField</value>
<value>deleteCustomField</value>
<value>getListConfigField</value>
<value>getListCofigFieldValue</value>
<value>getListCustomField</value>
<value>.....</value>
</list>
</property>
</bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/open/*"/>
<bean class="com.XXX.commons.api.open.XXXRequestInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
六、在Controller中添加Swagger相关注解,配置如下:
1、在Controller类上的注解如下:
@Api(value = "user", tags = "User Category", description = "User endpoint")
注:此注解可以写到所有Controller继承的BaseController上,否则需要在每个Controller上都加上此注解。
2、方法注解GET请求范例:
@Resource(name = "userServiceImpl")
private IUserService2ApiService userService2Api;
@RequestMapping(value = "getListRelationItem",
method = RequestMethod.GET,
produces = "application/json")
// consumes = "application/x-www-form-urlencoded")
@ApiOperation(
value = "获取用户XX关系列表接口",
notes = "返回用户对应的Id和使用状态.</br>" +
"Method: GET</br>" +
"Error Code: </br>" +
"<font color=\"red\">3000</font>: 参数错误</br>" +
"<font color=\"red\">3004</font>: 服务异常</br>" +
"<font color=\"red\">3005</font>: 操作失败</br>",
response = RelationItemList.class
)
public void getListRelationItem(@ModelAttribute GetListRelationItemInput input) {
//处理参数
if(Utils.isNull(input)){
input = new GetListRelationItemInput();
}
//设置用户id
input.setUserId(super.parseRequestHeaderInfo().getUserId());
//验证参数
if(!this.verifyParam(input)){
super.outputException(ExceptionConstants.PARAMETER_ERROR.getCode(),
ExceptionConstants.PARAMETER_ERROR.getMsg());
return;
}
//调用业务方法
CommonBusinessOutput output = null;
try {
output = this.userService2Api.getListRelationItem(
new CommonBusinessInput<>(input));
} catch (Exception e) {
super.LOGGER.error("GetListRelationItemController-getListRelationItem:", e);
super.outputException(ExceptionConstants.SERVER_EXCEPTION.getCode(),
ExceptionConstants.SERVER_EXCEPTION.getMsg());
return;
}
//处理服务异常
if(null == output){
super.outputException(ExceptionConstants.SERVER_EXCEPTION.getCode(),
ExceptionConstants.SERVER_EXCEPTION.getMsg());
return;
}
//处理业务异常
if(!output.isReturnStatus()){
ExceptionConstants e = this.handleBizException(output);
super.outputException(e.getCode(), e.getMsg());
return;
}
if(null == output.getData()){
super.outputData();
return;
}
super.outputData(output.getData());
}
3、方法注解POST请求范例:
@RequestMapping(value = "updateUser",
method = RequestMethod.POST,
produces = "application/json",
consumes = "application/json")
@ApiOperation(
value = "更新用户信息接口",
notes = "此接口可更新主表信息、位置表信息、主表扩展信息.</br>" +
"Method: POST</br>" +
"Error Code: </br>" +
"<font color=\"red\">3000</font>: 参数错误</br>" +
"<font color=\"red\">3004</font>: 服务异常</br>" +
"<font color=\"red\">3005</font>: 操作失败</br>",
response = UserS2Api.class
)
public void updateUser(@RequestBody UpdateUserInput input) {
//处理参数
if(Utils.isNull(input)){
input = new UpdateUserInput();
}
//设置用户id
input.setOwnByUserId(super.parseRequestHeaderInfo().getUserId());
//验证参数
if(!this.verifyParam(input)){
super.outputException(ExceptionConstants.PARAMETER_ERROR.getCode(),
ExceptionConstants.PARAMETER_ERROR.getMsg());
return;
}
//调用业务方法
CommonBusinessOutput output = null;
try {
output = this.userService2Api.updateUser(
new CommonBusinessInput<>(input));
} catch (Exception e) {
super.LOGGER.error("UpdateCardController-updateCard:", e);
super.outputException(ExceptionConstants.SERVER_EXCEPTION.getCode(),
ExceptionConstants.SERVER_EXCEPTION.getMsg());
return;
}
//处理服务异常
if(null == output){
super.outputException(ExceptionConstants.SERVER_EXCEPTION.getCode(),
ExceptionConstants.SERVER_EXCEPTION.getMsg());
return;
}
//处理业务异常
if(!output.isReturnStatus()){
ExceptionConstants e = this.handleBizException(output);
super.outputException(e.getCode(), e.getMsg());
return;
}
if(null == output.getData()){
super.outputData();
return;
}
super.outputData(output.getData());
}
注:1、方法参数必须以自定义对象接收,GET请求使用@ModelAttribute注解,POST请求使用@RequestBody 注解;
2、方法返回值只能是以下情况:无返回值、返回对象、返回List<对象>。若方法无返回值,则@ApiOperation注解中response参数值为Void.class;若方法返回值为对象,则response参数值为对象名.class;若方法返回值为List<对象>,则response参数值为对象名.class,并新增参数responseContainer,值为"List",example:response = 对象名.class,responseContainer="List"。
七、部署项目,访问以下地址:
http://host:port/swagger-ui.html
如果您觉得博主写的文章对您有帮助,可以请博主喝杯茶哦,O(∩_∩)O~
博主:诸葛本不亮
简介:毕业后做过多年程序猿、架构设计、项目经理、部门总监,待过传统软件公司,也在大型互联网公司负责过平台研发部,在这个行业浸淫十多年,在系统架构、SaaS平台搭建、项目管理以及部门管理等方面有着多年的一线实践经验。
目前与好友合伙创办了一个软件工作室,提供各类系统解决方案、咨询服务及技术合作,企业软件(SaaS平台、企业应用、商城、微信公众号及小程序开发)定制开发服务,大数据服务(数据采集及清洗、数据分析等),以及程序猿职业规划及转型咨询服务(程序猿转架构师、转项目管理、转技术管理等,可以提供相应的一线资料帮助您成功转型,获得大厂offer)。
微信号:danwang2138