SpringBoot集成Swagger
基于springboot配置swagger
3步走:
1.添加坐标(pom.xml)
<!--Swagger相关--> <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> <!--swagger-models 1.5.21及以上版本可以排除Swagger2异常:java.lang.NumberFormatException:For input string:""--> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.22</version> </dependency>
2.编写Swagger配置类
@Configuration @EnableSwagger2 public class SwaggerConfig { /** 开放接口 */ public static final String TAG_PUBLIC = "public"; /** 认证接口 */ public static final String TAG_AUTH = "auth"; /** 测试接口 */ public static final String TAG_TEST = "test"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).useDefaultResponseMessages(false) .apiInfo(apiInfo()).tags( new Tag(TAG_AUTH,"认证接口"), new Tag(TAG_PUBLIC,"开放接口(无需认证)"), new Tag(TAG_TEST,"测试接口") ) .produces(new HashSet<>(Arrays.asList("application/json"))).select() .apis(RequestHandlerSelectors.basePackage("com.mytech.demo.controller")) .paths(PathSelectors.any()).build(); } /** * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个 * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("SpringBootDemo 文档") //公司网址 .termsOfServiceUrl("http://www.wantong-tech.net") //版本号 .version("1.0") .build(); } }
3.编写Controller
@RestController @Api(tags = SwaggerConfig.TAG_TEST) @RequestMapping(SwaggerConfig.TAG_TEST) public class TestController { private static final String URL = "http://127.0.0.1:6666/"; @Autowired RestTemplate restTemplate; @PostMapping("template") @ApiOperation(value = "测试RestTemplate", notes = "RestTemplate测试") public String testRestTemplate(){ String requestUrl = "test/getString"; String response = restTemplate.getForObject(URL + requestUrl, String.class); return response; } }
另附: Swagger常用注解
在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下:
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下