丝袜哥 --- swagger的使用

一、是什么?

swagger,俗称丝袜哥,是用来生成接口文档的。没有使用swagger的时候,你写完后端接口,得自己将后端接口地址一个个地整理出来,告诉别人这个接口是干嘛的,要传哪些参数,正常情况下返回的参数是咋样的,非正常情况返回的又是咋样的。很麻烦有木有?有了丝袜哥,你只需要简单地加上几个注解,然后会有一个丝袜哥的ui界面,里面就包含了接口的所有信息,灰常地方便。

二、 怎么用?

以下操作基于springboot项目。

1. 添加依赖:

<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相关注解:

@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

3. 配置swagger:

新建一个配置类,对swagger进行配置:

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zhu.demo.swagger")) // 这个包下的会被swagger扫描到
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger") // swagger-ui展示的标题
                        .description("这是一个测试springboot整合swagger的项目") // swagger-ui页面的描述
                        .version("1.0") // api版本
                        .contact(new Contact("联系我","www.baidu.com","[email protected]")) // 联系方式
                        .license("lisence_description") // license
                        .licenseUrl("http://www.baidu.com") // license地址
                        .build());
    }
}

这个配置类对swagger做了一些基础的配置,最重要的就是扫描路径,即basePackage,其他都是页面上展示的东西。配置完这个,然后启动,访问:localhost:端口/swagger-ui.html,就可以看到如下页面:

4. 接口中使用swagger:

假如我现在在swagger能扫描到的包下新建如下几个类:

@Data
public class User {
    private long userId;
    private String userName;
    private String userPassword;
    private int userAge;
}
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/{userId}")
    public String query(@PathVariable("userId") Long userId){
        User user = new User();
        user.setUserId(userId);
        user.setUserName("testName");
        user.setUserPassword("testPassword");
        user.setUserAge(18);
        return JSONObject.toJSONString(user);
    }

    @PostMapping("/addUser")
    public String add(User user){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "0");
        jsonObject.put("message", "success");
        jsonObject.put("user", user);
        return jsonObject.toJSONString();
    }
}

你重启项目,再次访问swagger-ui,你会发现,页面中就已经有这两个接口了,如下:

点击try it out,就可以对接口进行测试了。但是,这样看起来怪怪的,因为没有接口的说明,也没有字段的说明,字段是否能为空也没有限制,响应示例也没有。

5. 加controller的说明:

在UserController类上加上注解:

@Api(tags = "用户模块")
public class UserController {
      ……
}

加上这个之后,界面就变成这样了:

6. 其他注解:

  • @ApiOperation("获取用户信息"):加在方法上,表示该接口是干嘛的,括号里面的是该方法的说明;

  • @ApiParam(name="userId",value="用户id",required=true, defaultValue = "1"):加在方法参数上,说明该参数是什么意思,是否必须,还可以设置一个默认值;

如果参数是对象,那么怎么搞?比如上面的add方法,参数是User对象,那么就在user类上用如下注解:

  • @ApiModel(value="User",description="用户对象"):加在User类上,说明这个对象是干啥的

  • @ApiModelProperty(value="用户名",name="userName",example="律政先锋"):加在user类属性上,说明这个字段是干啥的

这样,在接口中就会显示这些参数的释义了。

7. 显示model:

我们还可以直接将整个User类暴露在接口文档中,只需要在add方法中,加上@RequestBody,那么在页面中就会显示model了。

加上配置后的代码如下:

@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {

    @ApiOperation("获取用户信息") // 接口描述
    @GetMapping("/{userId}")
    public String query(@ApiParam(name="userId",value="用户id",required=true) @PathVariable("userId") Long userId){
        User user = new User();
        user.setUserId(userId);
        user.setUserName("testName");
        user.setUserPassword("testPassword");
        user.setUserAge(18);
        return JSONObject.toJSONString(user);
    }

    @ApiOperation("新增用户信息") // 接口描述
    @PostMapping("/addUser")
    public String add(@RequestBody User user){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "0");
        jsonObject.put("message", "success");
        jsonObject.put("user", user);
        return jsonObject.toJSONString();
    }
}
@Data
@ApiModel(value="User",description="用户对象")
public class User {
    @ApiModelProperty(value="用户id",name="userId",example="123")
    private long userId;
    @ApiModelProperty(value="用户名",name="userName",example="律政先锋")
    private String userName;
    @ApiModelProperty(value="用户密码",name="userPassword",example="lvzf")
    private String userPassword;
    @ApiModelProperty(value="用户年龄",name="userAge",example="18")
    private int userAge;
}

最终效果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章