2、Swagger

1、前言

接口文档对于前后端开发人员都十分重要。尤其近几年流行前后端分离后接口文档又变成重中之重。接口文档固然重要,但是由于项目周期等原因后端人员经常出现无法及时更新,导致前端人员抱怨接口文档和实际情况不一致。

很多人员会抱怨别人写的接口文档不规范,不及时更新。但是当自己写的时候确实最烦去写接口文档。这种痛苦只有亲身经历才会牢记于心。

如果接口文档可以实时动态生成就不会出现上面问题。

Swagger可以完美的解决上面的问题。

2、开发

①、添加jar依赖

springboot starter 依赖版本控制在2.5.6下。

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

②、添加注解

在SpringBoot的启动类中添加@EnableSwagger2注解。

添加此注解后表示对当前项目中全部控制器进行扫描。应用Swagger2

@SpringBootApplication
@EnableSwagger2
public class MyApp {
    public static void main(String [] args){
        SpringApplication.run(MyApp.class,args);
    }
}

③、访问swagger-ui

启动项目后在浏览器中输入http://ip:port/swagger-ui.html即可以访问到swagger-ui页面,在页面中可以可视化的进行操作项目中所有接口。

访问swagger-ui.html后可以在页面中看到所有需要生成接口文档的控制器名称。

④、swagger配置

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket getDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(swaggerDemoApiInfo())
                .select()
                .build();
    }
    private ApiInfo swaggerDemoApiInfo(){
        return new ApiInfoBuilder()
                .contact(new Contact("文档名字", "http://www.bjsxt.com", "xxx@163.com"))
                //文档标题
                .title("这里是Swagger的标题")
                //文档描述
                .description("这里是Swagger的描述")
                //文档版本
                .version("1.0.0")
                .build();
    }
}

⑤、Swagger常用注解

1、@Api是上注解。

控制整个类生成接口信息的内容。

@Api(tags = {"mydemo"},description = "描述")

 

2、@ApiOperation是方法上注解

对方法进行总体描述。

@ApiOperation(value="接口描述",notes = "接口提示信息")

 

3、@ApiParam是在方法参数前面。

用于对参数进行描述或说明是否为必添项等说明

public People getPeople(Integer id, @ApiParam(value="姓名",required = true) String name, String address)

 

4、@ApiModel是写在实体类上。

@ApiModel(value = "人类",description = "描述")
public class People { ...}

5、@ApiModelProperty是用属性上。

用于当对象作为参数时定义这个字段的内容。

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

或者
@ApiModelProperty(value = "姓名")
private String name;

 

 

 

posted @ 2022-07-05 11:15  jason饼干大怪兽  阅读(38)  评论(0)    收藏  举报