【SpringBoot】十六、SpringBoot中整合Swagger2

接口文档在我们日常开发工作中起到不可或缺的作用,特别是前后端分离的项目,需要使用接口文档来进行通信,而 Swagger2 是开源免费使用的,是一个减轻我们工作量的一款不错的工具

1、引入 Swagger2 依赖

<!-- swagger2 -->
<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、Swagger2 配置文件 SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                // 扫描路径
                .apis(RequestHandlerSelectors.basePackage("com.meet.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        // 标题
                        .title("Swagger项目管理")
                        // 描述
                        .description("Swagger项目管理接口测试文档")
                        // 版本号
                        .version("1.0.0")
                        // 联系人信息
                        .contact(new Contact("lizhou","http://127.0.0.1:8080/swagger-ui.html","[email protected]"))
                        // 使用协议
                        .license("The Apache License")
                        .licenseUrl("https://swagger.io/")
                        .build());
    }
}

我们首先使用 @Configuration 注解注明这是一个配置类
再使用 @EnableSwagger2 注解开启 Swagger2
然后配置一个 Docket Bean,在这个 Bean 中,配置扫描包的路径,即就是 Controller 类的路径
ApiInfo 中主要配置网站的信息,例如标题,描述,联系人,使用协议等信息

3、开始使用

启动项目,访问:

http://localhost:8080/swagger-ui.html

swagger2界面
在这里可以看到所有扫描到的 API 接口了

4、拓展知识

@Api() 用于类,表示标识这个类是swagger的资源
@ApiOperation() 用于方法,表示一个http请求的操作
@ApiParam() 用于方法,参数,字段说明,表示对参数的添加元数据(说明或是否必填等)
@ApiModel() 用于类,表示对类进行说明,用于参数用实体类接收
@ApiModelProperty() 用于方法,字段,表示对model属性的说明或者数据操作更改
@ApiIgnore() 用于类,方法,方法参数,表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法,表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

例如:

1、@Api() 注解

@Controller
@Api(tags = "添加好友相关接口")
@RequestMapping("addFriend")
public class AddFriendController {
	...
}

api注解
2、@ApiOperation() 注解
ApiOperation注解
如您在阅读中发现不足,欢迎留言!!!

发布了100 篇原创文章 · 获赞 321 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40065776/article/details/105658563