Swagger的使用
文章目录
- swagger是什么?有什么用?
- 如何使用?
swagger是什么?有什么用?
Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
有三个重要的作用:
- 将项目中所有的接口展现在页面上,这样后端程序员就不需要专门为前端使用者编写专门的接口文档;
- 当接口更新之后,只需要修改代码中的 Swagger 描述就可以实时生成新的接口文档了,从而规避了接口文档老旧不能使用的问题
- 通过 Swagger 页面,我们可以直接进行接口调用,降低了项目开发阶段的调试成本。
最终测试页面:
大概是这个样子的,可以直接进行测试,不需要写前端页面。
如何使用?
- 引入依赖
<project.swagger.version>3.0.0</project.swagger.version><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>${project.swagger.version}</version></dependency>
- 配置文件
在项目下键一个config包,写一个类用来做swagger的配置
代码:
@Configurationpublic class SwaggerConfiguration { public Docket creatRestApi(){ return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("springboot整合swagger3的接口文档") .description("描述图书馆管理的接口文档") .contact(new Contact("非凡boot","https://www.dyit.com","dyit@16.com")) .version("1.0") .build(); }}
- dto中添加描述信息
@Schema(description = "DTO对象")@Data@AllArgsConstructor@NoArgsConstructorpublic class HttpResp { @Schema(description = "后台返回代码") private int code; @Schema(description = "后台返回信息") private String msg; @Schema(description = "后台返回数据") private Object results; @Schema(description = "后台返回数据的时间") private Date date;}
- controller类中添加swagger信息
@Tag(name = "出版社模块")@RestController@RequestMapping("/api/publisher")public class PublisherController { @Autowired private IPublisherService ips; @Operation(summary = "获取所有出版社信息方法") @GetMapping("/findAll") public HttpResp findAll(){ List<Publisher> list = ips.findAll(); HttpResp dto = new HttpResp(HttpMsg.SUCCESS.getCode(), HttpMsg.SUCCESS.getMsg(), list,new Date()); return dto; }}
- 启动类中添加注解
@SpringBootApplication@Slf4j@EnableOpenApipublic class Main { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Main.class);// springApplication.setBannerMode(Banner.Mode.OFF); springApplication.run(args); log.debug("启动了Main"); }}
-
启动项目
-
页面搜索
此处的ssm是在.yml中配置的项目名 -
接口测试
如图:
结果:
注意:后面的 / 不能省略
参考链接:知乎