整合Swagger

HeJin大约 1 分钟Spring全家桶SpringBoot精讲细讲

官网:https://swagger.io/open in new window

image-20210512154738551
image-20210512154738551

引入依赖

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

配置类

Swagger3Config

@EnableOpenApi
@Configuration
public class Swagger3Config {

    @Bean
    public Docket initDocket(Environment env) {
        //设置要暴漏接口文档的配置环境
        Profiles profile = Profiles.of("dev", "test");
        boolean flag = env.acceptsProfiles(profile);
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hejin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot入门到精通")
                .description("飞过秋天")
                .contact(new Contact("飞过秋天", "https://dazhulin.gitee.io/", "dazhulin233@163.com "))
                .version("2.0")
                .build();
    }

}

application.yaml

spring:
  profiles:
    active: dev

访问页面

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

image-20210512161517531
image-20210512161517531

添加更多的文档信息

@Api(tags = "用户的crud操作api")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("根据用户id获得用户信息")
    @GetMapping("/user/{id}")
    public User findUserById(@PathVariable("id") @ApiParam("用户Id") int id){
        return userService.findUserById(id);
    }

    @ApiOperation("分页查询用户")
    @GetMapping("/user")
    public PageBean<User> findAllUser(){
        // 分页
        PageHelper.startPage(1, 2);
        List<User> userList = userService.findAllUser();

        return new PageBean<>(userList);
    }

    @ApiOperation("主页跳转")
    @GetMapping("/")
    public String index(){
        return "hello thymeleaf";
    }

}

结果:

image-20210512163451065
image-20210512163451065

更换UI

引入依赖

<dependency>
    <groupId>com.github.caspar-chen</groupId>
    <artifactId>swagger-ui-layer</artifactId>
    <version>1.1.3</version>
</dependency>

访问 http://localhost:8080/docs.html

image-20210512163929048
image-20210512163929048

YApi接口管理平台

https://hellosean1025.github.io/yapi/index.htmlopen in new window

image-20210512164449709
image-20210512164449709