Spring Boot引入Swagger并对界面进行美化

Swagger是一个接口文档生成工具,在前后端分离的开发中经常会用到,下面就来介绍下Swagger的使用:

引入依赖

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

配置Swagger

新建一个SwaggerConfig文件,输入

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("这里是描述信息")
                .contact(new Contact("JoeyHua", "https://home.cnblogs.com/u/joeyhua", "1601939052@qq.com"))
                .version("1.0")
                .build();
    }
}

使用注解

在项目的Application文件中添加@EnableOpenApi注解

@EnableOpenApi
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication .class, args);
	}

}

在Controller文件中添加@Api@ApiOperation注解

@Api(tags = "Demo")
@RestController
@RequestMapping("/demo")
public class DemoController {

    @ApiOperation("sayHello")
    @GetMapping("/sayHello")
    public String sayHello() {
        return "Hello";
    }
}

运行程序,浏览器访问http://ip:port/swagger-ui/index.html即可看到效果

美化Swagger文档界面

原生的Swagger文档界面有些简陋,可以使用knife4j美化界面,只需引入依赖即可

<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <artifactId>knife4j-spring-boot-starter</artifactId>
  <version>2.0.9</version>
</dependency>

这里要注意,knife4j的页面地址和原生地址不同,为http://ip:port/doc.html#/home,访问即可看到效果

小福利

最近写了一个前端Service文件自动生成工具,输入Swagger文档的地址即可自动生成Service文件,支持主流的HTTP客户端库,如axios和umi-request,支持生成TS文件,感兴趣的同学可以看一下。
github地址:https://github.com/huajiayi/openapi-tool
相关博客:https://www.cnblogs.com/joeyhua/p/15357143.html

posted @ 2021-09-30 18:13  JoeyHua  阅读(1026)  评论(0编辑  收藏  举报