新項目使用Swagger UI自動生成接口文檔,不需要頻繁更新接口文檔,保證接口文檔與代碼的一致,值得學習。本文記錄swaggerUi與springboot整合的步驟。
依賴添加
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
新增swagger配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
//apiInfo指定測試文檔基本信息,這部分將在頁面展示
.apiInfo(apiInfo())
.select()
//apis() 控制哪些接口暴露給swagger,
// RequestHandlerSelectors.any() 所有都暴露
// RequestHandlerSelectors.basePackage("com.info.*") 指定包位置
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
//基本信息,頁面展示
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("測試項目標題")
.description("接口描述")
//聯系人實體類
.contact(
new Contact("名字", "網址", "郵箱")
)
//版本號
.version("1.0.0-SNAPSHOT")
.build();
}
}
在Controller類上增加swagger配置
@RestController
@RequestMapping
//Api注解,描述信息 可通過tag進行分類
@Api(value = "HelloController", description = "HelloController")
public class HelloController {
@PostMapping("/addPerson")
//方法描述
@ApiOperation(notes = "添加人員", value = "addPerson")
public Person addPerson(
@ApiParam(name = "name", value = "姓名") @RequestParam("name") String name,
@ApiParam(name = "age", value = "年齡") @RequestParam("age") Integer age) {
Person person = new Person();
person.setAge(age);
person.setName(name);
return repository.save(person);
}
}
以上配置完成之后,直接啟動項目,訪問地址:localhost:8080/swagger-ui.html,即可打開如下頁面
image.png
Controller下的所有接口得到展示。展開其中一個可以看到接口詳情:
image.png
十分強大的工具,只需簡單注解即可生成接口文檔,代碼入侵小。