swagger

简介

生成在线接口文档

SpringBoot集成Swagger

新建一个Springboot项目

image-20201007214331690

添加依赖

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

编写一个hello

新建一个controller包下编写一个控制器

package com.jmu.swaggertest.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(value="/hello")
    public String Hello(){
        return "hello";
    }
}

集成Swagger

新建一个config包,编写一个配置类

package com.jmu.swaggertest.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2 //开启swagger2
public class MyConfig {
    
}

启动Springboot访问

http://localhost:8080/swagger-ui.html

因为源码中的是swagger-ui.html所以访问这个地址

image-20201007220609312

image-20201007215356068

Swagger配置

Swagger配置扫描接口

在MyConfig中配置

@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(true)//是否启动swagger,正式上线关闭
            .select()
            //RequestHandlerSelectors 配置要扫描接口的方式
            //basePackage :指定要扫描的包
            .apis(RequestHandlerSelectors.basePackage("com.jmu.swaggertest.controller"))
            //过滤什么路径
            .paths(PathSelectors.ant("/hello/**"))//只扫描hello下的controller
            .build();
}

Swagger配置Models

@RestController
public class HelloController {
    //只要我们的接口中返回值是实体类,就会返回到Swagger中
    @PostMapping(value = "/user")
    public User user(){
        return new User();
    }
}
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    private String name;
    @ApiModelProperty("用户密码") //由于是私有属性,所有要写get/set swagger那边才会显示
    private String pwd;

    public String getName() {
        return name;
    .....

image-20201007224814826

定义接口说明

定义在类上:@Api
定义在方法上:@ApiOperation
定义在参数上:@ApiParam

@Api(description="讲师管理")
@RestController
@RequestMapping("/admin/edu/teacher")
public class TeacherAdminController {
    @Autowired
    private TeacherService teacherService;
    @ApiOperation(value = "所有讲师列表")
    @GetMapping
    public List<Teacher> list(){
        return teacherService.list(null);
    }
    @ApiOperation(value = "根据ID删除讲师")
    @DeleteMapping("{id}")
    public boolean removeById(
            @ApiParam(name = "id", value = "讲师ID", required = true)
            @PathVariable String id){
        return teacherService.removeById(id);
    }
}
posted @ 2020-10-07 22:53  DJ同学  阅读(79)  评论(0编辑  收藏  举报