Swagger和Springboot整合


目录:

  1. Swagger简介
  2. Springboot整合Swagger

参考/来源:

Swagger简介

Swagger是一款可以快速生成符合RESTful风格API并进行在线调试的插件。

Swagger常用注解

  • @Api:修饰整个类,描述Controller的作用;
  • @ApiOperation:描述一个类的一个方法,或者说一个接口;
  • @ApiParam:单个参数描述;
  • @ApiModel:用对象来接收参数;
  • @ApiProperty:用对象接收参数时,描述对象的一个字段;
  • @ApiResponse:HTTP响应其中1个描述;
  • @ApiResponses:HTTP响应整体描述;
  • @ApiIgnore:使用该注解忽略这个API;
  • @ApiError :发生错误返回的信息;
  • @ApiImplicitParam:一个请求参数;
  • @ApiImplicitParams:多个请求参数。

Springboot整合Swagger

依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

注意:这里Springboot的版本不能太高,否则可能导致Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException错误。对于2.6.1版本的Swagger,使用Springboot的2.5.1版本正常,但使用Springboot的2.6.1`会报上述错误。

配置类

配置类中添加@EnableSwagger2注解来启用Swagger2,apis()定义了扫描的包路径

这两个方法是配置类的基础方法,返回值必须为Docket和ApiInfo。

还可以进行其他自定义方法配置。

@Configuration
@EnableSwagger2
public class SwaggerConfig {
  	/*
  	swagger的bean实例为:Docket
  	*/
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(buildApiInf())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
            .paths(PathSelectors.any())
            .build();
    }
  	
  	/*
  	接口信息设置:ApiInfo
  	*/
    private ApiInfo buildApiInf() {
        return new ApiInfoBuilder()
            .title("系统RESTful API文档")
            .contact(new Contact("mrbird", "https://mrbird.cc", "852252810@qq.com"))
            .version("1.0")
            .build();
    }
}

控制类

不需要生成API的方法或者类,只需要在上面添加@ApiIgnore注解即可

@Api(value = "用户Controller")
@Controller
@RequestMapping("user") //注意,这里一定不能少!!!否则报错类型转换错误
public class UserController {

    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody String hello() {
        return "hello";
    }

    @ApiOperation(value = "获取用户信息", notes = "根据用户id获取用户信息")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/{id}")
    public @ResponseBody User getUserById(@PathVariable(value = "id") Long id) {
        User user = new User();
        user.setId(id);
        user.setName("mrbird");
        user.setAge(25);
        return user;
    }

    @ApiOperation(value = "获取用户列表", notes = "获取用户列表")
    @GetMapping("/list")
    public @ResponseBody List<User> getUserList() {
        List<User> list = new ArrayList<>();
        User user1 = new User();
        user1.setId(1l);
        user1.setName("mrbird");
        user1.setAge(25);
        list.add(user1);
        User user2 = new User();
        user2.setId(2l);
        user2.setName("scott");
        user2.setAge(29);
        list.add(user2);
        return list;
    }

    @ApiOperation(value = "新增用户", notes = "根据用户实体创建用户")
    @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User")
    @PostMapping("/add")
    public @ResponseBody Map<String, Object> addUser(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        return map;
    }

    @ApiOperation(value = "删除用户", notes = "根据用户id删除用户")
    @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path")
    @DeleteMapping("/{id}")
    public @ResponseBody Map<String, Object> deleteUser(@PathVariable(value = "id") Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        return map;
    }

    @ApiOperation(value = "更新用户", notes = "根据用户id更新用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "Long", paramType = "path"),
        @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User") })
    @PutMapping("/{id}")
    public @ResponseBody Map<String, Object> updateUser(@PathVariable(value = "id") Long id, @RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "success");
        return map;
    }

}

注意,上述在Controller类上的@RequestMapping注解,一定不能少,否则会报错Failed to convert value of type ‘java.lang.String’ to required type ‘java.lang.Integer’; nested exception is java.lang.NumberFormatException: For input string: “swagger-ui”

访问默认Swagger页面

启动项目,访问http://localhost:8080/swagger-ui.html即可看到Swagger给我们生成的API页面:


文章作者: 小小千千
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小千千 !
评论
  目录