1、创建springboot项目
步骤见https://blog.csdn.net/u012069313/article/details/122319305
2、添加Maven依赖
swagger2.9及以下版本添加如何依赖:
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
swagger2.10开始支持两种模式:WebFlux,WebMVC,添加以下依赖(以WebMVC为例):
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.10.5</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.10.5</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-webmvc</artifactId>
<version>2.10.5</version>
</dependency>
3、application.yml中添加配置:
swagger:
title: swagger-test
description: swagger-test
version: 1.0
terms-of-service-url: http://127.0.0.1:8080
contact:
name: swagger-test
url: http://127.0.0.1:8080
email: test@chaoyue.com
4、添加配置类
@EnableSwagger2WebMvc //swagger2.9及以下版本为@EnableSwagger2
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.chaoyue.swagger2test.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("api接口文档")
.contact(new Contact("test","http://127.0.0.1:8080","test@chaoyue.com"))
.version("1.0")
.description("api描述")
.build();
}
}
5、Controller中添加注解
@Api("HelloController")
@RestController
public class HelloController {
@GetMapping(value = "/user")
public String getUser() {
return "user";
}
}
6、测试
输入测试地址:http://localhost:8080/swagger-ui.html