Swagger2 的配置与开启
开启
Swagger2 的使用分为配置和开启两部分,其中配置是特殊化定制Swagger文档最为重要的一部分,而开启则只是将配置放入解析器中,直接使用@EnableSwagger2
注解开启Swagger2的使用
配置
我们需要通过对Docket对象的配置来实现我们的特异化需求,所以在配置之前,对Docket要有一定的了解。
Docket
我们先看Docket对象的注释,翻译过来为:
Docket 是一个构建器,旨在成为Springfox框架的主要接口。提供合理的默认值和方便的配置方法。
链式调用
在Docket对属性的配置方法中都是返回Docket,作为一个配置类,它具备链式调用的特性。
构造函数
Docket有且仅有一个构造函数,构造函数需要传入DocumentationType
对象,该参数用来确定文档的类型,在其中可选择三种文档,
当然,你也可以通过DocumentationType
的构造函数定制你想要的文档。在Swagger2中,则会使用DocumentationType
的常量 SWAGGER_2
来确定我们使用的文档。
apiInfo()
方法
用来配置一些文档的基本信息,就算所有内容无意义,对Swagger2和项目无影响。
了解到这些,继续配置Swagger2。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* TODO
*
* @author ben
* @version 1.0
* @date 2022/9/13 11:23
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
//配置文档信息
private ApiInfo apiInfo() {
Contact contact = new Contact("ben", "https://xxxxxx.com", "Swagger2Config@SpringBoot.com");
return new ApiInfo(
"Ben的学习总结", // 标题
"Swagger2Config", // 描述
"v1.0", // 版本
"https://xxxxxx.com", // 组织链接
contact, // 联系人信息
"Apach 2.0 许可", // 许可
"https://xxxxxx.com", // 许可连接
new ArrayList<>()// 扩展
);
}
}
配置前:
配置后:
下一节继续剖析Docket。