springboot项目中配置swagger
http://localhost:9999/swagger-ui.html
1、配置依赖
在pom文件中增加以下依赖,
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2-verion}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2-verion}</version>
</dependency>
2、创建配置类Swagger2Config
@EnableSwagger2
@Configuration
public class Swagger2Config {
@Bean
public Docket api() {
/** SWAGGER_2版本 */
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
/** 选择那些路径和api会生成document */
.select()
/** com.hashtech.uaa.uaa 此包下的所有api */
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
/** 对所有路径进行监控 */
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("UAA 统一认证鉴权系统 API")
.description("https://git.oschina.net/sealde/springboot-javaconfig/tree/dev2")
.termsOfServiceUrl("https://git.oschina.net/sealde/springboot-javaconfig/tree/dev2")
.version("1.0")
.build();
}
}
3、对接口和实体类添加注释,常见的标记如下:
@Api()用于类;
标识这个类是swagger的资源
tags–表示分组说明标签
@ApiOperation()用于方法;
表示一个http请求的操作
value用于方法描述
notes用于提示内容
@ApiModel()用于实体类
表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
@ApiModelProperty()用于实体类字段
表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiImplicitParam() 用于 controller 方法
表示单独的请求参数
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
@ApiImplicitParams() 用于 controller 方法,包含多个 @ApiImplicitParam
@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
测试代码如下所示
@RestController
@Api(value = "DemoController", description = "测试代码")
public class DemoController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ApiOperation(value = "测试", notes = "测试", httpMethod = "GET")
public String test(){
return "success";
}
}
4、打开swagger地址
http://localhost:9999/swagger-ui.html
如下图所示即配置完成。