Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务, 也就是将项目中所有想要暴露的接口展现在页面上,并且可以进行接口调用和测试的服务。
- 引入maven依赖
<!-- web project-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 启动类中加入注解:@EnableOpenApi 和 @EnableWebMvc
@SpringBootApplication
@EnableOpenApi
@EnableWebMvc
@MapperScan(basePackages = "org.example.mapper")
public class App {
public static void main( String[] args ) {
SpringApplication.run(App.class, args);
}
}
- 启动项目并访问 http://localhost:8080/swagger-ui/index.html
就可以看到默认配置页面。
- 实际开发中往往需要一些个性化的展示,就需要自定义一个swagger的配置类:可以参考官网说明使用更多个性化功能。
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/**
* define display information
* @return
*/
private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("Swagger testing")
.description("My description")
.contact(new Contact("dummy email","test link","test@my.com"))
.version("3.0")
.build();
}
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select().apis(RequestHandlerSelectors.basePackage("org.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
- 重新启动项目就可以看到自定义的信息
至此,Swagger的基本使用就已经完成了。