在spring boot项目中整合swagger的核心步骤包括:引入依赖、配置docket bean、添加注解以实现api文档化,并可通过安全认证和隐藏接口等进一步优化。1. 引入maven依赖,推荐使用springfox-boot-starter 3.0.0版本;2. 创建配置类swaggerconfig,定义docket bean并设置api基本信息、扫描路径和包;3. 启动应用后访问/swagger-ui/index.html查看文档界面;4. 添加securityschemes和securitycontexts以支持jwt认证;5. 使用@apiignore注解或paths()方法隐藏特定api;6. 遇到问题时检查版本兼容性、路径配置及依赖冲突,确保正确启用@enableopenapi注解。
在Spring Boot项目里整合Swagger,说白了就是为了把我们那些散落在代码里的API接口,用一种清晰、交互性强的方式展现出来。核心操作其实就那么几步:引入依赖、配置一个Docket Bean,然后通过注解告诉Swagger哪些接口需要被文档化。这玩意儿一旦配好,你就能在浏览器里直接看到所有接口,还能在线调试,对前后端联调的效率提升,那可不是一星半点。我个人觉得,这几乎是现代微服务开发里不可或缺的一环,能省下大量沟通成本。
通常,我开始一个新项目时,第一步就是把Swagger的依赖加进去。这就像给你的API文档找个好管家,省心。
1. 引入Maven依赖
如果你用的是Maven,在pom.xml里添加:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
这里我推荐使用springfox-boot-starter 3.0.0版本,它基于OpenAPI 3规范,相对老旧的Swagger2来说,功能更完善,也更符合当前趋势。当然,如果你的项目比较老,还在用Spring Boot 1.x或者Spring Cloud Finchley之类的,可能得退回到springfox-swagger2和springfox-swagger-ui的2.x版本,那时候配置起来稍微有点不一样,但核心思想是通的。
2. 创建Swagger配置类
接下来,你需要创建一个配置类来告诉Spring Boot如何初始化Swagger。我一般会命名为SwaggerConfig。
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; // 对应Springfox 3.0.0 import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableOpenApi // 启用OpenAPI支持,如果是Springfox 2.x,这里是@EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) // 指定API文档类型为OpenAPI 3.0 .apiInfo(apiInfo()) // 设置API基本信息 .select() // 选择要生成文档的API .apis(RequestHandlerSelectors.basePackage("com.yourcompany.project.controller")) // 指定扫描的包 // .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) // 或者扫描带有@RestController注解的类 .paths(PathSelectors.any()) // 扫描所有路径 // .paths(PathSelectors.regex("/api/.*")) // 或者只扫描/api/开头的路径 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("你的项目API文档") // 文档标题 .description("这是一个关于XXXX项目的API接口文档,希望能帮助你快速理解和使用接口。") // 详细描述 .contact(new Contact("你的名字", "http://yourwebsite.com", "your.email@example.com")) // 维护者信息 .version("1.0") // API版本 .build(); } }
这里面最关键的就是那个Docket Bean。DocumentationType.OAS_30表示我们用的是OpenAPI 3规范。apiInfo()方法就是用来配置文档的标题、描述、联系方式和版本号这些元数据。select()方法是重点,它定义了哪些API会被Swagger扫描并生成文档。我通常用RequestHandlerSelectors.basePackage()来指定控制器所在的包,这样比较精确。当然,你也可以用withClassAnnotation(RestController.class)来扫描所有带有@RestController注解的类,或者用PathSelectors.regex()来过滤特定的URL路径。
3. 访问Swagger UI
配置完成后,启动你的Spring Boot应用。然后,在浏览器中访问:http://localhost:8080/swagger-ui/index.html (如果你用的是Springfox 3.0.0)。如果是Springfox 2.x版本,通常是http://localhost:8080/swagger-ui.html。
你就能看到一个漂亮的交互式API文档界面了。
说实话,大部分实际项目里,API都是需要认证的,比如用JWT Token。如果Swagger文档不能模拟这个认证过程,那在线调试的功能就大打折扣了。所以,给Swagger加上安全认证支持,这几乎是必做项。
我们可以在Docket配置中添加securitySchemes和securityContexts。
import java.util.Collections; import java.util.List; import springfox.documentation.service.ApiKey; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.service.contexts.SecurityContext; // ... 其他import和类定义不变 ... @Configuration @EnableOpenApi public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.yourcompany.project.controller")) .paths(PathSelectors.any()) .build() .securitySchemes(securitySchemes()) // 添加安全方案 .securityContexts(securityContexts()); // 添加安全上下文 } private List<ApiKey> securitySchemes() { // 配置JWT认证方式:在请求头中传递Token return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header")); } private List<SecurityContext> securityContexts() { return Collections.singletonList( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("/.*")) // 对所有路径都生效 .build() ); } private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Collections.singletonList(new SecurityReference("Authorization", authorizationScopes)); } // ... apiInfo() 方法不变 ... }
这里我做了几件事:
配置好后,你会发现Swagger UI界面上多了一个“Authorize”按钮。点击它,输入你的JWT Token(通常是Bearer开头),然后你再调试接口时,请求头里就会自动带上这个Token了。这真的太方便了,省去了每次手动复制粘贴Token的麻烦。
有时候,我们不希望所有的API都暴露在Swagger文档里,或者想让UI界面看起来更符合品牌风格。这些需求,Swagger也考虑到了。
1. 隐藏特定API
最简单粗暴的方法是使用@ApiIgnore注解。如果你有一个控制器或者一个方法,你压根不想让它出现在文档里,直接在类或方法上加上@ApiIgnore就行。
import springfox.documentation.annotations.ApiIgnore; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @ApiIgnore // 整个控制器都不会出现在文档中 public class InternalController { @GetMapping("/internal/data") public String getInternalData() { return "Sensitive internal data"; } } @RestController public class PublicController { @GetMapping("/public/info") public String getPublicInfo() { return "Public information"; } @ApiIgnore // 这个方法不会出现在文档中 @GetMapping("/public/hidden-method") public String getHiddenMethod() { return "This method is hidden."; } }
另一种方法是,在Docket配置中通过paths()进行更细粒度的控制,比如只暴露/api/v1/开头的接口:
// ... Docket 配置中 ... .paths(PathSelectors.regex("/api/v1/.*")) // 只显示/api/v1/开头的路径 // .paths(PathSelectors.ant("/api/v1/**")) // 也可以用ant风格的路径匹配 .build();
这样,那些不符合规则的接口就不会出现在文档里了。
2. 定制Swagger UI
Springfox 3.0.0默认的UI路径是/swagger-ui/index.html。如果你想修改这个路径,或者进行一些UI上的简单定制,可以通过application.properties或application.yml来配置。
# application.properties springdoc.swagger-ui.path=/docs springdoc.api-docs.path=/api-docs # 改变原始API JSON的路径
这里我用了springdoc的配置,因为Springfox 3.0.0在内部实际上是基于springdoc-openapi的。通过springdoc.swagger-ui.path,你可以把访问路径改成http://localhost:8080/docs。
如果你想更深入地定制UI,比如修改样式、添加Logo,那就得稍微麻烦一点了。你需要下载Swagger UI的静态资源,然后放到Spring Boot的src/main/resources/static目录下,覆盖掉默认的资源文件。这通常涉及到修改index.html,引入自定义的CSS或JS文件。我个人觉得,除非有非常强的品牌要求,否则默认的UI已经足够用了,没必要折腾太多。毕竟,我们的主要目标是API文档的可用性,而不是UI有多花哨。
在我自己的项目实践中,集成Swagger虽然总体顺利,但也遇到过一些让人头疼的小问题。
1. 版本冲突或不兼容
这是最常见的问题。比如,你用了Spring Boot 2.6.x,却引入了老旧的Springfox 2.x版本,或者Springfox 3.0.0和某些Spring Cloud版本之间会有依赖冲突。
症状: 应用启动失败,报错信息通常是NoClassDefFoundError、NoSuchMethodError或者Bean创建失败。Swagger UI无法访问,或者显示空白。
解决方案:
检查Spring Boot和Springfox版本兼容性。 Springfox 3.0.0通常与Spring Boot 2.x系列(尤其是2.3.x及以上)配合较好。如果遇到问题,可以尝试升级或降级Spring Boot版本,或者调整Springfox的版本。
排除传递性依赖。 有时,其他库会引入旧版本的Swagger依赖。你可以在pom.xml中使用
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency>
清理Maven/Gradle缓存。 mvn clean install 或 gradle clean build 后,删除本地Maven仓库中相关的Springfox/Swagger目录,再重新构建。
2. Swagger UI无法访问或No handler found
你启动了应用,但访问/swagger-ui/index.html或/swagger-ui.html时却出现404错误。
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
或者,如果你用的是Springfox 3.0.0,并且Spring Boot版本较高,可以尝试使用springdoc-openapi-ui替代springfox-boot-starter,它对新版Spring Boot的兼容性更好。
3. API文档内容不全或显示异常
你发现有些控制器或方法没有出现在文档中,或者参数、返回值显示不正确。
总的来说,Swagger的集成过程相对成熟,大部分问题都集中在版本兼容性和路径配置上。只要细心检查配置和依赖,通常都能顺利解决。
以上就是Spring Boot整合Swagger详细配置教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号