本文讲解springboot中如何集成swagger

swagger2是一个可以构建和调试RESTful API文档的组件,利用swagger2的注解可以快速的在项目中构建Api文档,并且提供了测试API的功能

集成swagger

引入swagger依赖
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>
配置swagger
/**
 * @auther: chenmingyu
 * @date: 2018/12/2 21:39
 * @description:
 */
@Configuration
@EnableSwagger2
public class Swagger2Configration {

    /**
     * 创建api文档
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.my.swagger"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * api文档页面展示信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger组件")
                .description("测试api文档")
                .contact(new Contact("mingyu", "www.chenmingyu.top", null))
                .version("1.0")
                .build();
    }
}

@configration 标识这是一个配置类

@Bean 将docket对象注入到spring容器

@EnableSwagger2 开启swagger2

apis 表示swagger需要扫描的包

PathSelectors.any() 表示路径选择器匹配所有路径

contact() 作者信息

示例
/**
 * @auther: chenmingyu
 * @date: 2018/12/2 21:43
 * @description:
 */
@RestController
@RequestMapping("/test")
@Api(tags ="用户信息接口")
public class UserController {

    @GetMapping("/user")
    @ApiOperation(value="查询所有", notes="查询所有用户信息")
    public List<User> queryUsers(){
        List<User> userList = new ArrayList<>();
        IntStream.range(0, 5).forEach(i->{
            User user = new User();
            user.setId(i);
            user.setUserName("cmy");
            user.setPassWord("passWord");
            userList.add(user);
        });
        return userList;
    }
}
@Data
@ApiModel(value="用户对象")
class User {

    private Integer id;
    @ApiModelProperty(value="用户名称",name="userName")
    private String userName;

    @ApiModelProperty(value="密码",name="passWord")
    private String passWord;
}
启动项目,查看swagger页面

文档地址 http://localhost:8080/swagger-ui.html

重用注释
@Api() 用于类;表示标识这个类是swagger的资源 
tags–表示说明 
value–也是说明,可以使用tags替代 

@ApiOperation() 用于方法;表示一个http请求的操作 
value用于方法描述 
notes用于提示内容 

@ApiParam() 用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等) 
name–参数名 
value–参数说明 
required–是否必填

@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收 
value–表示对象名 

@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 
value–字段说明 
name–重写属性名字 
dataType–重写属性类型 
required–是否必填 
example–举例说明 
hidden–隐藏

@ApiImplicitParam() 用于方法 
表示单独的请求参数

@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam 
name–参数ming 
value–参数说明 
dataType–数据类型 
paramType–参数类型 
example–举例说明

@ApiIgnore
作用于方法上,使用这个注解swagger将忽略这个接口