3、微服务整合Swagger3.0 - 网关Gateway聚合接口
一、什么是Swagger
Swagger 是一款restful接口的文档在线自动生成+功能测试功能软件;
Swagger的目标是为rest apis 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。
二、springfox-swagger和springfox-swagger-ui
Swagger 是一种规范。
springfox-swagger 是基于 Spring 生态系统的该规范的实现。
springfox-swagger-ui 是对 swagger-ui 的封装,使其可以使用 Spring 的服务。
三、SpringBoot使用Swagger
1、pom文件引入依赖,版本2和3自行选择,这里的${swagger.fox.version}选了3.0.0
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.fox.version}</version>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.fox.version}</version>
</dependency>
2、配置swagger
/**
* @author cch
* @create 2024-01-26 18:47
*/
@Configuration
@EnableSwagger2 //开启Swagger2的自动配置
@Import({SwaggerWebConfiguration.class}) //3.0.0版本访问是: /swagger-ui/index.html
public class SwaggerConfig{
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 要扫描的API(Controller)基础包,注意basePackage改成自己每个项目的路径
.apis(RequestHandlerSelectors.basePackage("com.cch"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact("cch","","");
return new ApiInfoBuilder()
//标题
.title("管理API文档")
//接口描述
.description("后台api")
.contact(contact)
.version("3.0.0").build();
}
}
Swagger2访问地址:http://{ip}:{port}/swagger-ui.html
Swagger3访问地址:http://{ip}:{port}/swagger-ui/index.html
3、配置资源映射
public class SwaggerWebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
/** swagger-ui 地址 */
//3.0.0版本访问是: /swagger-ui/index.html
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
4、在Application启动类加入注解@EnableSwagger2
@EnableSwagger2
@SpringBootApplication
public class FilesApplication {
public static void main(String[] args) {
SpringApplication.run(FilesApplication.class, args);
}
}
5、测试swagger
@ApiOperation("测试Swagger")
@GetMapping("/testSwagger")
public Object info(){
return "{\"username\":\"admin\",\"password\":\"admin123\"}";
}
测试效果:
访问地址:http://{ip}:{port}/swagger-ui/index.html
注:如果不能访问,启动时报错:
Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException
请在application.properties中加入以下这段信息:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher |