前言
在集成springfox-swagger2之前,我也尝试着集成了swagger-springmvc,方式差不多,但是swagger-springmvc相对麻烦一点,因为要把它的静态文件copy到自己的项目中。所以还是用新版本的。
至于两者有什么不同,为什么进行版本变更请参见官方说明文档
方法如下
这里先写下需要的pom.xml配置(我引用的2.4.0,相对稳定)
1
2
3
4
5
6
7
8
9
10
|
<
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
>
|
还需要在spring-mvc.xml中添加映射静态的配置:
1
|
<mvc:default-servlet-handler />
|
然后就是swagger2的配置类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package
com.xingguo.logistics.swagger;
import
org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableSwagger2
public
class
SwaggerConfig {
@Bean
public
Docket buildDocket(){
return
new
Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.select() .apis(RequestHandlerSelectors.basePackage(
"com.xingguo.logistics.controller"
))
//controller路径
.paths(PathSelectors.any())
.build();
}
private
ApiInfo buildApiInf(){
return
new
ApiInfoBuilder()
.title(
"xingguo大标题"
)
.description(
"springmvc swagger2"
)
.build();
}
}
|
然后运行项目,输入自己的url。
http://{ip}:{port}/{projectname}/swagger-ui.html#/
我的url:
http://localhost:8989/logistics/swagger-ui.html#/
然后就可以看到效果图:
它会把按照controller,把所有的接口都加载进来。
我的目录结构如图:
然后,就是接口名称和参数的说明:
常用注解:
- @Api()
用于类名
- @ApiOperation()
用于方法名
- @ApiParam()
用于参数说明
- @ApiModel()
用于实体类
- @ApiModelProperty
用于实体类属性
更详细的说明请参见官方注解说明文档
使用方法如图:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@Controller
//类上使用@Api
@Api
(value=
"用户controller"
,description=
"用户相关操作"
)
public
class
UserController {
@RequestMapping
(value=
"index"
,method=RequestMethod.POST)
//方法上使用@ApiOperation
@ApiOperation
(value=
"首页"
,notes=
"跳转到首页"
)
//参数使用@ApiParam
public
Object getIndex(
@ApiParam
(name=
"topic实体"
,value=
"json格式"
,required=
true
)
@RequestBody
Topic topic){
//业务内容,被我删除了,请忽略,主要看上面的注解
Object obj =
new
Object();
return
obj;
}
}
|
1
2
3
4
5
|
//一般添加个@ApiModel()就可以,看情况使用里面的属性
@ApiModel
(value=
"Topic"
, discriminator =
"foo"
, subTypes = {Topic.
class
})
public
class
Topic{
}
|
效果图如下:
我在springboot中也集成了swagger2,集成方式基本相同,使用方式也基本一样。请参考Spring Boot集成springfox-swagger2构建restful API的方法教程
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对脚本之家的支持。