java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot集成swagger、knife4j及常用注解

springboot集成swagger、knife4j及常用注解的使用

作者:康提扭狗兔

这篇文章主要介绍了springboot集成swagger、knife4j及常用注解的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1. 集成swagger2

1.1 引入依赖

        <!-- 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>

1.2 添加Swagger配置

关键 RequestHandlerSelectors.basePackage(“com.gz”)

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInfo())
                .select()
                // 要扫描的API(Controller)基础包
                .apis(RequestHandlerSelectors.basePackage("com.gz"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo buildApiInfo() {
        Contact contact = new Contact("gz","","");
        return new ApiInfoBuilder()
                .title("测试swagger-springbootdemo API文档")
                .description("springbootdemo后台api")
                .contact(contact)
                .version("1.0.0").build();
    }
}

通常情况下,swagger配置放在common模块中,别的模块需要集成swagger时,只需要引入common模块就行,因此需要将SwaggerConfiguration类在META-INF/spring.facories文件里进行配置,这样才能将SwaggerConfiguration类注册进IOC容器。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.gzdemo.springbootdemo.config.SwaggerConfiguration

但是如果SwaggerConfiguration类在启动类的同级目录或子目录下,就不需要此项配置了。

1.3 controllers和models

@RequestMapping("/test")
@RestController
public class TestController {
    
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
    
    @PostMapping("/addUser")
    public Map addUser(@RequestBody UserDto userDto){
        Map<String, Object> result = new HashMap<>();
        UserDto userDto1 = new UserDto();
        userDto1.setName("ceshi");
        userDto1.setAge(23);
        userDto1.setPhone("15700000001");
        userDto1.setEmail("111@qq.com");
        result.put("data",userDto1);
        result.put("msg","添加成功");
        return result;
    }
}
@Data
public class UserDto {
    private String name;
    private String phone;
    private Integer age;
    private String email;
}

1.4 浏览器访问

浏览器访问 http://localhost:8080/swagger-ui.html

2. Swagger常用注解

2.1 Swagger常用注解

在Java类中添加Swagger的注解即可生成Swagger接口文档,常用Swagger注解如下:

属性取值作用
paramType查询参数类型
path以地址的形式提交数据
query直接跟参数完成自动映射赋值
body以流的形式提交 仅支持POST
header参数在request headers 里边提交
form以form表单的形式提交 仅支持POST
dataType参数的数据类型 只作为标志说明,并没有实际验证
Long
String
name接收参数名
value接收参数的意义描述
required参数是否必填
true必填
false非必填
defaultValue默认值

2.2 测试

我们在TestController和UserDto中添加Swagger注解,代码如下所示:

@RequestMapping("/test")
@RestController
@Api(value = "测试控制器",tags = "test")
public class TestController {

    @ApiOperation("用户测试hello")
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public Map addUser(@RequestBody UserDto userDto){
        Map<String, Object> result = new HashMap<>();
        UserDto userDto1 = new UserDto();
        userDto1.setName("ceshi");
        userDto1.setAge(23);
        userDto1.setPhone("15700000001");
        userDto1.setEmail("111@qq.com");
        result.put("data",userDto1);
        result.put("msg","添加成功");
        return result;
    }
}

@Data
public class UserDto {

    @ApiModelProperty(value="姓名",required = true)
    private String name;

    @ApiModelProperty(value="手机号",required = true)
    private String phone;

    @ApiModelProperty(value="年龄",required = true)
    private Integer age;

    @ApiModelProperty(value="邮箱",required = true)
    private String email;
}

启动应用,访问 http://localhost:8080/swagger-ui.html

3. 集成knife4j

3.1 添加依赖

        <!-- 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>
        
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.9</version>
        </dependency>

3.2 添加注解

3.3 浏览器访问

http://localhost:8080/doc.html

4. Swagger常用注解案例

@RestController
@Api(tags = "课表的相关接口")
@RequestMapping("/lessons")
public class LearningLessonController {

}

    @GetMapping("/now")
    @ApiOperation("查询我正在学习的课程")
    public LearningLessonVO queryMyCurrentLesson() {
        return lessonService.queryMyCurrentLesson();
    }

    @ApiOperation("查询指定课程的学习记录")
    @GetMapping("/course/{courseId}")
    public LearningLessonDTO queryLearningRecordByCourse(
            @ApiParam(value = "课程id", example = "2") @PathVariable("courseId") Long courseId){
        return recordService.queryLearningRecordByCourse(courseId);
    }

@Data
@ApiModel(description = "学习记录")
public class LearningRecordFormDTO {

    @ApiModelProperty("小节类型:1-视频,2-考试")
    @NotNull(message = "小节类型不能为空")
    @EnumValid(enumeration = {1, 2}, message = "小节类型错误,只能是:1-视频,2-考试")
    private SectionType sectionType;

    @ApiModelProperty("课表id")
    @NotNull(message = "课表id不能为空")
    private Long lessonId;

    @ApiModelProperty("对应节的id")
    @NotNull(message = "节的id不能为空")
    private Long sectionId;

    @ApiModelProperty("视频总时长,单位秒")
    private Integer duration;

    @ApiModelProperty("视频的当前观看时长,单位秒,第一次提交填0")
    private Integer moment;

    @ApiModelProperty("提交时间")
    private LocalDateTime commitTime;
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文