Swagger使用

阅读数:14 评论数:0

跳转到新版页面

分类

python/Java

正文

Swagger作用:

(1)接口的文档在线自动生成。

(2)功能测试

Maven

<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>

创建Swagger2配置类

package com.swaggerTest;
 
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
/**
 * Swagger2配置类
 * 在与spring boot集成时,放在与Application.java同级的目录下。
 * 通过@Configuration注解,让Spring来加载该类配置。
 * 再通过@EnableSwagger2注解来启用Swagger2。
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * 
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}

添加文件内容

@Api():用在类上,说明该的作用

@Api(value = "用户博客", tags = "博客接口")
public class NoticeController {

}

@ApiOperation():注解来给API增加方法说明

@GetMapping("/detail")
@ApiOperation(value = "获取用户详细信息", notes = "传入notice" , position = 2)
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}

@ApiParam():用于方法,参数,字段说明

@PostMapping("/remove")
@ApiOperation(value = "逻辑删除", notes = "传入notice", position = 7)
public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
   boolean temp = noticeService.deleteLogic(Func.toIntList(ids));
   return R.status(temp);
}

@ApiImplicitParams():用在方法上包含一组参数说明

@GetMapping("/list")
@ApiImplicitParams({
   @ApiImplicitParam(name = "category", value = "公告类型", paramType = "query", dataType = "integer"),
   @ApiImplicitParam(name = "title", value = "公告标题", paramType = "query", dataType = "string")
})
@ApiOperation(value = "分页", notes = "传入notice", position = 3)
public R<IPage<Notice>> list(@ApiIgnore @RequestParam Map<String, Object> notice, Query query) {
   IPage<Notice> pages = noticeService.page(Condition.getPage(query), Condition.getQueryWrapper(notice, Notice.class));
   return R.data(pages );
}

@ApiImplicitParam():用来注解方法入参

paramType:指定参数放在哪个地方

header:请求参数放置于Request Header,使用@RequestHeader获取

query:请求参数放置于请求地址,使用@RequestParam获取

path:(用于restful接口)-->请求参数的获取:@PathVariable

body:(不常用)

form(不常用)

name:参数名

 

dataType:参数类型

 

required:参数是否必须传

true | false

value:说明参数的意思

 

defaultValue:参数的默认值

 

@ApiResponses:用来表示一组响应

@GetMapping("/detail")
@ApiOperation(value = "获取用户详细信息", notes = "传入notice" , position = 2)
@ApiResponses(value = {@ApiResponse(code = 500, msg= "INTERNAL_SERVER_ERROR", response = R.class)})
public R<Notice> detail(Integer id) {
   Notice detail = noticeService.getOne(id);
   return R.data(detail );
}

@ApiModel():用于类,表示对类接收的参数

@ApiModelProperty():用于方法、字段,表示对model属性说明

@Data
@ApiModel(value = "BladeUser ", description = "用户对象")
public class BladeUser implements Serializable {

   private static final long serialVersionUID = 1L;

   @ApiModelProperty(value = "主键", hidden = true)
   private Integer userId;

   @ApiModelProperty(value = "昵称")
   private String userName;

   @ApiModelProperty(value = "账号")
   private String account;

   @ApiModelProperty(value = "角色id")
   private String roleId;
 
   @ApiModelProperty(value = "角色名")
   private String roleName;

}

@ApiIgnore()用于类、方法、方法参数,表示这个方法或者类被忽略。

@ApiResponse: 用在@ApiResponses中,一般用于表达一个错误的响应信息。

  | code :数字

  | message:信息

  | response:抛出异常在类

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解描述时)

  | @ApiModelProperty:描述一个model的属性

package com.swaggerTest.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
 
/**
 * 一个用来测试swagger注解的控制器
 * 注意@ApiImplicitParam的使用会影响程序运行,如果使用不当可能造成控制器收不到消息
 * 
 * @author SUNF
 */
@Controller
@RequestMapping("/say")
@Api(value = "SayController|一个用来测试swagger注解的控制器")
public class SayController {
    
    @ResponseBody
    @RequestMapping(value ="/getUserName", method= RequestMethod.GET)
    @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回")
    @ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")
    public String getUserName(@RequestParam Integer userNumber){
        if(userNumber == 1){
            return "张三丰";
        }
        else if(userNumber == 2){
            return "慕容复";
        }
        else{
            return "未知";
        }
    }
    
    @ResponseBody
    @RequestMapping("/updatePassword")
    @ApiOperation(value="修改用户密码", notes="根据用户id修改密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    public String updatePassword(@RequestParam(value="userId") Integer userId, @RequestParam(value="password") String password, 
            @RequestParam(value="newPassword") String newPassword){
      if(userId <= 0 || userId > 2){
          return "未知的用户";
      }
      if(StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)){
          return "密码不能为空";
      }
      if(password.equals(newPassword)){
          return "新旧密码不能相同";
      }
      return "密码修改成功!";
    }
}

启动spring boot程序后,访问http://localhost:8080/swagger-ui.html