Swagger(配置、使用、注解)

Swagger

之前实习时候使用过,这里总结一下
Swagger是全球最大的开源API规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。

Swagger2是2.x版本,目前已经到了3.x,使用的主要区别是引入的依赖


SpringBoot整合

引入依赖

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

Swagger配置类

        @Configuration
        @EnableSwagger2
        public class Swagger2 {
            //为了自定义Docket中的apiInfo信息
            @Bean
            public Docket createRestApi() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(apiInfo())
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.moke.validated.controller"))
                        .paths(PathSelectors.any())
                        .build();
            }

            private ApiInfo apiInfo() {
                return new ApiInfoBuilder()
                        .title("Swagger2--api文档")
                        .description("接口测试")
                        .version("1.0")
                        .build();
            }
        }

接口加上注解

	@PostMapping("/addUser")
    @ApiOperation(value = "添加用户信息",notes = "数据校验测试接口")
    public String addUser(@Validated(UserValidationGroup2.class) @RequestBody User user){
        String res = "用户名:"+user.getName()+",密码:"+user.getPassword()+",邮箱:"+user.getEmail();
        return res;
    }

API文档

浏览器访问http://localhost:8080/swagger-ui.html,就可以看到API文档,并对接口进行测试:
在这里插入图片描述


注解说明

上面的使用中,只使用了 @ApiOperation 注解,这里总结一下其他的常用注解:

注解 作用
@Api 修饰整个类,用于描述Controller
@ApiOperation 描述类的方法,或者说一个接口
@ApiParam 单个参数描述
@ApiModel 用对象来接收参数,作用于类
@ApiProperty 用对象接收参数时,描述一个对象的字段
@ApiResponse HTTP响应的一个描述
@ApiResponses HTTP响应的整体描述
@ApiIgnore Swagger忽略该api
@ApiError 发生错误返回的信息
@ApiParamImplicit 一个请求参数
@ApiParamsImplicit 多个请求参数

猜你喜欢

转载自blog.csdn.net/MOKEXFDGH/article/details/107591472