Swagger使用

Swagger介绍

Swagger是一款接口文档在线自动生成和功能测试的工具,是一个规范和完整的框架

Swagger的主要作用
接口文档在线自动生成,进行接口的功能测试

Swagger使用

首先导入swagger的依赖jar包pom.xml 文件

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

创建Swagger2的配置类

@Configuration
@EnableSwagger2 //注解启动swagger2
public class SwaggerConfig {
    @Bean
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * select()
     * apis()函数返回一个ApiSelectorBuilder实例,指定接口暴露给swagger
     * paths
     * build()
     */
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
               .apis(RequestHandlerSelectors.basePackage("com.example.myspringboot.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建API基本信息(展现在文档页中)
     * title: 标题 description:文档描述
     * version:版本      contact:作者
     * termsOfServiceUrl:服务URL
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Swagger2接口文档示例")
                .description("新闻管理系统接口文档的API")
                .version("1.0")
                .contact("战天下")
                .termsOfServiceUrl("")
                .build();
    }
}

在Controller层添加注解

@Slf4j
@RestController
@EnableSwagger2//让swagger生成接口文档
@Api(value="用户管理接口文档")
public class UserController extends BaseControllerSupport {
    @Autowired
    private UserService userService;
    String  errorMsg=null;
    @ApiOperation(value="显示所有用户")
    @GetMapping("/user/showUser")
    @ResponseBody
    public ServerResponse showUser(){
        try{
            ServerResponse response = userService.showUser();
            return response;
        }catch(Exception e){
            errorMsg="获取数据异常";
            return ServerResponse.createByErrorMessageException(errorMsg,e);
        }
    }
    @ApiOperation(value="查找一个用户")
    @GetMapping("user/getUser/{id}")
    @ResponseBody
    public ServerResponse getUserById(@ApiParam(value="用户ID") @PathVariable("id") Integer id){
        ServerResponse response=userService.getUserById(id);
        return response;
    }
    @ApiOperation(value="用户登录")
    @PostMapping(value="/user/login")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="username",value="用户名",required=true,dataType = "String"),
            @ApiImplicitParam(paramType="query",name="password",value="密码",required=true,dataType = "String"),
    })
    public ServerResponse login(@RequestParam("username") String username, @RequestParam("password") String password ,HttpSession session){
        try {
            String ip="111222d114";
            System.out.println(ip);
            ServerResponse response=userService.login(username,password,ip);
            String msg=response.getMsg();
            if(response.isSuccess()){
                session.setAttribute(Const.CURRENT_USER,response);
                return ServerResponse.createBySuccess("登录成功");
            }
            return ServerResponse.createByErrorMessage(msg);
        }catch(Exception e){
            //异常处理,插入数据库返回前端errorMsg="用户登录时发生异常";
            errorMsg="用户登录时发生异常";
            return ServerResponse.createByErrorMessageException(errorMsg,e);
        }

    }

Swagger常用注解说明:

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

@APIOperation:方法说明

@ApilmplicitParams:用在方法上包含一组参数说明

@ApimplicitParam:用来给方法参数增加说明

@ApiParam:参数说明和@ApilmplicitParam中的value类似

@ApiResponses:表示一组响应

@ApiResponse:用在ApiResponses里,表达一个错误的响应信息

@ApiModel:藐视model的信息,一般是传入实体对象时无法使用ApimplicitParam

@ApiModelProperty:描述一个model的属性

其中@ApilmplicitParam参数说明:

paramType:指定参数的位置:header:请求头query:请求参数放在请求地址使用

path: --restful风格@PathVariable请求参数的获取body: 请求体form:

name:参数名

dataType:参数类型

required:参数是否必须传

value:说明参数的意思

defaultValue:参数的默认值

注:使用restful风格(GetMapping,PostMapping,PutMapping,DeleteMapping)来代替RequestMapping,如果一定使用RequestMapping,一定要指定method的类型,否则文档会生成很多没用的接口

文档访问地址:http://localhost:8080/swagger-ui.html(如果有项目名,要加上项目名称)

Swagger使用