SpringBoot整合Swagger2
1.首先导入pom依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.编写配置类,swagger访问地址是http://实际项目地址/swagger-ui.html
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//根据环境是否开启显示
@Value("${swagger.flag}")
private boolean flag;
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
//是否开启
.enable(flag)
//返回一个ApiSelectorBuider实例,用来控制那些接口暴露给Swagger显示
.select()
//配置需要扫描接口的位置
.apis(RequestHandlerSelectors.basePackage("com.sise.swagger.controller"))
//配置映射路径,只扫描的路径
.paths(PathSelectors.ant("/**"))//到这里就是一个ApiSelectorBuider实例
.build().apiInfo(new ApiInfoBuilder()
//设置标题
.title("SpringBoot整合Swagger")
//文档描述
.description("SpringBoot整合Swagger,详细信息......")
//版本号
.version("1.0")
//设置作者信息(name,url,email)
.contact(new Contact("啊啊啊啊","blog.csdn.net","aaa@gmail.com"))
//开源信息
.license("The Apache License")
//开源链接
.licenseUrl("http://www.baidu.com")
.build());
}
}
3.修改model类
//表示ApiModel,被swagger扫描
@ApiModel
public class User {
//用于方法,字段; 表示对model属性的说明
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiIgnore//忽略该字段
private String address;
//省略getter和setter
}
4.修改controller类
@RestController
//描述类/接口的用途
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
@GetMapping("/")
//为方法添加说明
@ApiOperation("根据id查询用户的接口")
//描述方法的参数,为参数添加说明
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
public User getUserById(@PathVariable Integer id) {
User user = new User();
user.setId(id);
return user;
}
}
5.结果图