SpringBoot简单整合Swagger2

Swagger是什么

Swagger 是一系列 RESTful API 的工具,通过 Swagger 可以获得项目的一种交互式文档,客户端 SDK 的自动生成等功能。

使用 Spring Boot 集成 Swagger 的理念是,使用注解来标记出需要在 API 文档中展示的信息,Swagger 会根据项目中标记的注解来生成对应的 API 文档。Swagger 被号称世界上最流行的 API 工具,它提供了 API 管理的全套解决方案,API 文档管理需要考虑的因素基本都包含,这里将讲解最常用的定制内容。

简单使用

1.创建springboot项目
2.引入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>

3.创建配置类:

@Configuration     //启动时加载此类
@EnableSwagger2  //表示此项目启用 Swagger API 文档
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 自行修改为自己的包路径
                .apis(RequestHandlerSelectors.basePackage("com.snow.hello"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("hello")
            .description("hello API 1.0 操作文档")
            .version("1.0")
            .termsOfServiceUrl("https://blog.csdn.net/shelleylittlehero/article/details/80621592")
            .contact(new Contact("littleHero","https://blog.csdn.net/shelleylittlehero/article/details/80621592","[email protected]"))
            .build();
    }
}

4.启动application;访问 http://localhost:8080/swagger-ui.html ,发现报错:
在这里插入图片描述

这是由于在项目中出现了一个很不起眼的错误:
在这里插入图片描述

注意:

需要注意的是:WebController中出现了@RequestMapping(name="/getUser")应为@RequestMapping(value="/getUser"),修改过之后可以访问页面,我推测,在Springboot启动过程中应该是对注解做了校验的;后期可以研究一下.

在这里插入图片描述

Swagger常用注解

作用范围 API 使用位置
协议集描述 @Api 用于 Controller 类上
协议描述 @ApiOperation 用在 Controller 的方法上
非对象参数集 @ApiImplicitParams 用在 Controller 的方法上
非对象参数描述 @ApiImplicitParam 用在 @ApiImplicitParams 的方法里边
响应集 @ApiResponses 用在 Controller 的方法上
响应信息参数 @ApiResponse 用在 @ApiResponses 里边
描述返回对象的意义 @ApiModel 用在返回对象类上
对象属性 @ApiModelProperty 用在出入参数对象的字段上