Swagger的简单使用
Swagger官网:https://swagger.io/
使用Swagger
环境:
- SringBoot版本:2.5.6
- Swagger版本:2.9.2
新建一个SpringBoot项目,导入Swagger依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
创建Swagger配置类
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
启动项目,访问路径:http://localhost:8080/swagger-ui.html
Swagger配置
可以进行的配置在springfox.documentation.spring.web.plugins.Docket类中。
在SwaggerConfig配置类中进行配置
// 配置Swagger的Docket的Bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
// 配置Swagger信息
public ApiInfo apiInfo() {
// 作者信息
Contact contact = new Contact("hllog", "https://www.cnblogs.com/hllog/", "123456@qq.com");
return new ApiInfo("hllog的Swagger API文档",
"专注于技术",
"v1.0",
"https://www.cnblogs.com/hllog/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
使用Swagger生成文档
@ApiModel("用户")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@ApiModelProperty("用户ID")
private Integer id;
@ApiModelProperty("用户名")
private String name;
@ApiModelProperty("密码")
private String password;
}
@RestController
public class HelloController {
@ApiOperation("简单的问候")
@GetMapping("/hello")
public String hello() {
return "Hello Swagger";
}
@ApiOperation("获取用户")
@PostMapping(value = "/user")
public User user() {
return new User();
}
@ApiOperation("对用户进行问候")
@GetMapping("/hello2")
public String hello2(@ApiParam("用户名") String name) {
return "Hello, " + name;
}
}
更多的Swagger注解参见io.swagger.annotations
包。
分类:
Swagger
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能