一、先添加 Swagger2 所需要的依赖包
<!--swagger2接口文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
二、创建一个配置文件
/**
*通过springfox 提供的Docket 对象,我们可以灵活的配置 Swagger 的各项属性。
*/
@Configuration
@EnableSwagger2 //@EnableSwagger2 是启用 Swagger2
public class Swagger2Config {
@Bean
public Docket createRestAPi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()//初始化并返回一个API选择构造器
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))//添加路径选择条件扫描接口-> basePackage(final String basePackage):返回一个断言(Predicate),该断言包含所有匹配basePackage下所有类的请求路径的请求处理器; any():返回包含所有满足条件的请求处理器的断言,该断言总为true; none():返回不满足条件的请求处理器的断言,该断言总为false
.paths(PathSelectors.any())//设置路径筛选 -> any():满足条件的路径,该断言总为true; none():不满足条件的路径,该断言总为false; regex(final String pathRegex):符合正则的路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试 APIS")
.description("了解更多请联系:")
.termsOfServiceUrl("http://www.xxxx.com")
.contact("180xxxx9005")
.version("1.0")
.build();
}
}
三、添加注解描述
1、先了解各个注解的功能
api | 使用位置 |
---|---|
@Api (常用) | 用于controller类上,修饰整个类 |
@ApiOperation(常用) | 用于controller里方法上,描述方法用途 |
@ApiImplicitParam (常用) | 用于controller里方法上,描述单独的请求参数 |
@ApiImplicitParams(常用) | 用于controller里方法上,描述复数的请求参数,里面是多个@ApiImplicitParams |
@ApiParam | 用于controller方法,参数,字段说明,表示对参数的添加元数据(说明或是否必填等) |
@ApiModel (常用) | 用于JavaBean上面,表示一个实体类,这种一般用在post创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 |
@ApiModelProperty(常用) | 用于实体类内方法,字段; 表示对model属性的说明 |
@ApiIgnore(常用) | 用于类,方法,方法参数上, 表示这个方法或者类被忽略 ;Swagger 文档不会显示拥有该注解的接口。 |
@ResponseHeader | 用在controller的方法上,响应头配置 |
@ApiResponse | 用在controller的方法上,响应集配置 |
@ApiResponses | 用在controller的方法上,多个响应集配置,里面是多个@ApiResponse |
2、好好说说各个注解的具体细节
1. @Api
主要属性
属性 类型 描述 tags String[] 控制器标签 description String 控制器描述(该字段被申明为过期)。 @Api("用户业务处理控制类 UserController") @RestController public class UserController { }
2. @ApiOperation
主要属性
属性 类型 描述 value String 接口说明。 notes String 接口发布说明。 tags String[] 标签。 response Class<?> 接口返回类型。 httpMethod String 接口请求方式。 @ApiOperation(value = "用户登录", notes = "注意参数格式",tags = "用户业务",httpMethod = "POST") @RequestMapping(path = {"/login"}, method = RequestMethod.POST) public String login() { return userService.login(username, password); }
3. @ApiImplicitParam
主要属性
属性 类型 描述 paramType String 可选:
1. path:以地址的形式提交数据,根据 id 查询用户的接口就是这种形式传参。@PathVariable
2. query:Query string 的方式传参。@RequestParam
3. header:以流的形式提交。@RequestHeader
4. body: 请求体@RequestBody User user
5. form(不常用):以 Form 表单的形式提交dataType String 参数的数据类型。如:String、Integer… name String 参数名 value String 参数的描述 required 布尔 是否为必填参数 当前后端的传递参数的名称对应上之后,后台仍然无法接收到参数,这可能是因为我们没有加上request相关的说明,如@requestParam @requestBody 等等
@ApiOperation(value = "根据id查询用户信息", notes = "注意参数格式") @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", paramType = "path") @RequestMapping(path = {"/{userId:^[0-9]+}"}, method = RequestMethod.GET) public String getUserInfo(@PathVariable Integer userId) { return userService.queryById(userId); }
4. @ApiImplicitParams
有多个参数,就包含多少个@ApiImplicitParam
@ApiOperation(value = "用户登录", notes = "注意参数格式",tags = "用户业务",httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String"), @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String"), }) @RequestMapping(path = {"/login"}, method = RequestMethod.POST) public String login( String username,String password) { return userService.login(username, password); }
5. @ApiModel
描述一个实体类
@ApiModel(value = "FormRequestCategory",description = "用于提交分类信息") public class FormRequestCategory implements Serializable { }
使用
public String add(@ApiParam(required = true)@RequestBody FormRequestCategory formRequestCategory) { }
6. @ApiModelProperty
主要属性
属性 类型 描述 value String 属性字段说明。 name String 重写字段名称 dataType String 重写字段类型 required boolean 是否必填 example String 举个栗子 hidden boolean 是否在文档中隐藏该字段 allowEmptyValue boolean 是否允许为空 allowableValues String 该字段允许的传入的值 @ApiModel(value = "FormRequestCategory",description = "用于提交分类信息") public class FormRequestCategory implements Serializable { @ApiModelProperty(name = "name",value = "分类名称",dataType = "String",required = true,example = "水果") private String name; @ApiModelProperty(name = "description",value = "分类描述",required = true,example = "特价水果,仅限特价日使用") private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
四、运行SpringBoot
启动项目访问 http://127.0.0.1:8080/swagger-ui.html 就可以看到了,如下
如果页面报错或者后台 No mapping found for HTTP request ,多半是静态资源的问题,因为swagger-ui.html相关的所有前端静态文件都在springfox-swagger-ui-2.6.1.jar里面。Spring Boot自动配置本身不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。所以需要我们加上这个映射。
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/") registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") } }
—————————————————————————————————————————这样OK啦——