SpringBoot 项目中引入Swagger (Springfox)

当前springboot版本为2.6.2 ,springfox-boot-stater版本为3.0.0,本文通过springfox-boot-stater 来实现对springboot接口的管理,

参考文档:

默认访问地址修改的文档说明:http://springfox.github.io/springfox/docs/current/#changes-in-swagger-ui

maven中引入springfox-boot-stater

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-boot-starter</artifactId>
  <version>3.0.0</version>
</dependency>

编写配置文件

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yituomao.blog.back.controller")) // 指定扫描的包
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("YiTuoMao Blog 后台")
                .version("1.0")
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }
}

使用swagger相关注解进行API文档的相关生成

  • @Api(tags = "controller name")
  • @ApiOperation(value = "方法名称")
  • @ApiParam("参数说明")

例子:

controller:

@RestController
@Api(tags = "测试")
public class CommonController {
    @GetMapping("/hello")
    @ApiOperation(value = "hello文档")
    public String hello(@ApiParam("用户信息") User user, String name) {
        return "hello" + user.getUsername() + user.getPassword() + name;
    }
}

pojo:

public class User {
    // 通过 ApiModelProperty 指定字段说明
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
}

默认访问地址:http://localhost:8080/swagger-ui/index.html

posted @ 2022-01-05 21:31  GetcharZp  阅读(320)  评论(0编辑  收藏  举报