SpringBoot集成Swagger2与Swagger3的区别及说明
更新时间:2026年06月15日 09:51:03 作者:TheTsing
这段文章详细介绍了如何在项目中集成和配置Swagger,涵盖从引入Swagger依赖到设置访问路径的全过程,特别强调了Swagger 2与Swagger 3的区别,以及如何在项目中实现API文档的自动生成和管理
前言
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
总体目标是使客户端和文件系统作为服务器以同样的速度来更新。
文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。
Swagger 让部署管理和使用功能强大的 API 从未如此简单。
一、pom文件中引入Swagger依赖
Swagger2
<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>
Swagger3
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
二、Swagger配置
Swagger2
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 自行修改为自己的包路径
.apis(RequestHandlerSelectors.basePackage("com.tsing"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-api文档")
.description("swagger接入教程")
.version("1.0")
.contact(new Contact("TheTsing", "https://blog.csdn.net/qq_42375133?type=blog", "thetsing@foxmail.com"))
.build();
}
}
Swagger3
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.tsing"))
.paths(PathSelectors.any())
.build()
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Api Documentation")
.contact(new Contact("TheTsing", "http://www.baidu.com", "thetsing@foxmail.com"))
.version("1.0")
.build();
}
}
三、若配置有拦截器,应对Swagger做如下配置
Swagger2
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置swagger拦截器
registry.addInterceptor(new MyInterceptor())// 这里加入自己写的拦截器
.addPathPatterns("/**").
excludePathPatterns("/swagger-resources/**", "/webjars/**", "/swagger-ui.html/**", "/v2/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置swagger静态资源映射
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// 跨域支持
registry.addMapping("/**").allowedOriginPatterns("*").allowedMethods("*").allowCredentials(true);
}
}
Swagger3
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置swagger拦截器
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**").
excludePathPatterns("/swagger-resources/**", "/webjars/**", "/swagger-ui/**", "/v3/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 配置swagger静态资源映射
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// 跨域支持
registry.addMapping("/**").allowedOriginPatterns("*").allowedMethods("*").allowCredentials(true);
}
}
四、若项目中还有Token验证,则对应Swagger配置文件做如下修改
Swagger2
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 自行修改为自己的包路径
.apis(RequestHandlerSelectors.basePackage("com.tsing"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-api文档")
.description("swagger接入教程")
.version("1.0")
.contact(new Contact("TheTsing", "https://blog.csdn.net/qq_42375133?type=blog", "thetsing@foxmail.com"))
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList();
apiKeyList.add(new ApiKey("token", "token", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("token", authorizationScopes));
return securityReferences;
}
}
Swagger3
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.tsing"))
.paths(PathSelectors.any())
.build()
.protocols(newHashSet("https", "http"))
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Api Documentation")
.contact(new Contact("TheTsing", "http://www.baidu.com", "thetsing@foxmail.com"))
.version("1.0")
.build();
}
/**
* 设置授权信息
*/
private List<SecurityScheme> securitySchemes() {
ApiKey apiKey = new ApiKey("token", "token", In.HEADER.toValue());
return Collections.singletonList(apiKey);
}
/**
* 授权信息全局应用
*/
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("token", new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")})))
.build()
);
}
@SafeVarargs
private final <T> Set<T> newHashSet(T... ts) {
if (ts.length > 0) {
return new LinkedHashSet<>(Arrays.asList(ts));
}
return null;
}
}
五、访问路径
Swagger2和Swagger3的访问路径也有所不同:
- Swagger2:http://localhost:port/swagger-ui.html
- Swagger3:http://localhost:port/swagger-ui/index.html
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java中提供synchronized后为什么还要提供Lock
这篇文章主要介绍了Java中提供synchronized后为什么还要提供Lock,在Java中提供了synchronized关键字来保证只有一个线程能够访问同步代码块,下文更多相关资料需要的小伙伴可以参考一下2022-03-03
Spring Boot中使用Redis和Lua脚本实现延时队列的方案
通过使用Redis和Lua脚本,可以在Spring Boot环境中实现一个高效且可靠的延时队列系统,这种方法利用了Redis的有序集合数据结构和Lua脚本的原子性操作来确保任务的正确性和一致性,这篇文章主要介绍了Spring Boot中使用Redis和Lua脚本实现延时队列,需要的朋友可以参考下2024-05-05
java.lang.IllegalArgumentException:Invalid character&nb
本文介绍了java.lang.IllegalArgumentException: Invalid character found异常的解决,方法包括检查代码中的方法名,使用合适的HTTP请求方法常量,使用第三方HTTP库,检查请求URL以及使用调试和日志工具,通过这些方法,我们可以解决异常并确保网络应用程序的正常运行2023-10-10
基于bufferedreader的read()与readline()读取出错原因及解决
这篇文章主要介绍了bufferedreader的read()与readline()读取出错原因及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12


最新评论