关于 springBoot 使用 swagger2生成接口文档 的正确姿势

一、先添加 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

主要属性

属性类型描述
tagsString[]控制器标签
descriptionString控制器描述(该字段被申明为过期)。
  @Api("用户业务处理控制类 UserController")
  @RestController
  public class UserController {
  
  }

2. @ApiOperation

主要属性

属性类型描述
valueString接口说明。
notesString接口发布说明。
tagsString[]标签。
responseClass<?>接口返回类型。
httpMethodString接口请求方式。
    @ApiOperation(value = "用户登录", notes = "注意参数格式",tags = "用户业务",httpMethod = "POST")
  	@RequestMapping(path = {"/login"}, method = RequestMethod.POST)
  	public String login() {
   		return userService.login(username, password);
    }

3. @ApiImplicitParam

主要属性

属性类型描述
paramTypeString可选:
1. path:以地址的形式提交数据,根据 id 查询用户的接口就是这种形式传参。@PathVariable
2. query:Query string 的方式传参。@RequestParam
3. header:以流的形式提交。@RequestHeader
4. body: 请求体@RequestBody User user
5. form(不常用):以 Form 表单的形式提交
dataTypeString参数的数据类型。如:String、Integer…
nameString参数名
valueString参数的描述
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

主要属性

属性类型描述
valueString属性字段说明。
nameString重写字段名称
dataTypeString重写字段类型
requiredboolean是否必填
exampleString举个栗子
hiddenboolean是否在文档中隐藏该字段
allowEmptyValueboolean是否允许为空
allowableValuesString该字段允许的传入的值
  @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啦——

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值