Java knife4j swagger
1、官网
https://doc.xiaominfo.com/
2、pom
<!--引入Knife4j的官方start包,该指南选择Spring Boot版本<3.0,开发者需要注意-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
3、配置
package com.example.demo.config; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; @Configuration @EnableSwagger2WebMvc public class Knife4jConfiguration { @Bean(value = "dockerBean") public Docket dockerBean() { //指定使用Swagger2规范 Docket docket=new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() //描述字段支持Markdown语法 .description("# Knife4j RESTful APIs") .termsOfServiceUrl("https://doc.xiaominfo.com/") .contact("xiaoymin@foxmail.com") .version("1.0") .build()) //分组名称 .groupName("用户服务") .select() //这里指定Controller扫描包路径 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); return docket; } }
4、控制器
package com.example.demo.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @Api(tags = "首页模块") @RestController @RequestMapping("/index") public class IndexController { @ApiImplicitParam(name = "name",value = "姓名",required = true) @ApiOperation(value = "向客人问好") @GetMapping("hi") public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){ return ResponseEntity.ok("Hi:"+name); } }
5、模型
import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class ResponseDto { /** * 代码,0=成功,其它=失败 */ @ApiModelProperty(value = "代码,0=成功,其它=失败", position = 1) private int code = 0; /** * 描述 */ @ApiModelProperty(value = "描述", position = 2) private String msg; /** * 消息体 */ @ApiModelProperty(value = "消息体", position = 3) private Object data; /** * 成功,并返回消息体 * @param data * @return */ public static ResponseDto success(Object data) { ResponseDto dto = new ResponseDto(); dto.setData(data); dto.setMsg("接口访问成功"); return dto; } /** * 失败,返回消息内容 * @param msg * @return */ public static ResponseDto fail(String msg) { ResponseDto dto = new ResponseDto(); dto.setCode(1); dto.setMsg(msg); return dto; } }
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号