
springboot整合swagger进行测试
在父项目 在
发布日期:2021-05-25 12:33:57
浏览次数:38
分类:精选文章
本文共 2678 字,大约阅读时间需要 8 分钟。
Swagger文档生成与应用配置
1. 基本概念与环境搭建
在大型项目中,为了方便接口测试和文档生成,可以使用Swagger工具。Swagger是一种基于代码生成的API文档工具,支持多种请求类型包括GET、POST、PUT、DELETE等。通过Swift【Springfox】框架可以轻松集成Swagger功能。
2. 环境搭建(基于 Maven 项目结构)
2.1 创建模块结构
guli_parent
中,创建新的子模块service_base
,类型为Maven工程。service_base
模块的pom.xml
中添加必要的依赖。2.2 添加依赖
io.springfox springfox-swagger2 provided io.springfox springfox-swagger-ui provided
3. Swagger配置类创建
3.1 配置类实现
创建一个名为SwaggerConfig
的Java配置类,位于service_base
模块的src/main/java
包下。
package com.kaki.servicebase;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.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;@Configuration@EnableSwagger2public class SwaggerConfig { @Bean public Docket webApiConfig() { return new Docket(DocumentationType.SWAGGER_2) .groupName("webApi") .apiInfo(webApiInfo()) .select() .paths(Predicates.not(PathSelectors.regex("/admin/.*"))) .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } private ApiInfo webApiInfo() { return new ApiInfoBuilder() .title("网站-课程中心API文档") .description("本文档描述了课程中心微服务接口定义") .version("1.0") .contact(new Contact("java", "http://atguigu.com", "1123@qq.com")) .build(); }}
4. 在项目中使用Swagger
4.1 项目依赖管理
确保在需要使用Swagger的子模块中引入service_base
模块:
com.kaki service_base 0.0.1-SNAPSHOT
4.2 启动类注解配置
在启动类上添加以下注解:
@SpringBootApplication@ComponentScan(basePackages = "com.kaki")public class EduApplication { public static void main(String[] args) { SpringApplication.run(EduApplication.class, args); }}
4.3 Swagger访问路径
Swagger文档可以通过以下路径访问:
http://localhost:8001/swagger-ui.html
4.4 核心注解使用
在控制器类上添加以下注解,方便文档生成:
- 类级注解:
@Api
(描述控制器用途) - 方法级注解:
@ApiOperation
(描述方法功能) - 参数级注解:
@ApiParam
(描述参数属性)
5. 注意事项
- 在启动类中添加
@EnableSwagger2
注解,否则 Swagger文档将无法正常访问。 - 确保
SwaggerConfig
类和启动类的包名 prefix一致,以便扫描到配置类。
6. 示例使用
在service_edu
模块中使用SwaggerConfig
配置,可以看到生成的Swagger文档包含详细的接口定义和操作说明。
通过以上配置,开发者可以轻松生成并测试接口文档,支持多种请求类型,同时便于团队协作和项目文档管理。
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2025年04月18日 17时22分22秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!