Swagger
項(xiàng)目是一個(gè)可以將Restful
服務(wù)的接口api doc
可視化的工具,而且提供了在線調(diào)試api
的功能,對于開發(fā)的Restful
服務(wù)非常友好,因此可以將其集成到項(xiàng)目中來。
這里通過spring initializer
創(chuàng)建一個(gè)結(jié)構(gòu)簡單的spring boot
程序,來展示Swagger
的使用, 完整的項(xiàng)目示例參見:
創(chuàng)建一個(gè)
spring boot web
應(yīng)用,導(dǎo)入web
,jpa
,h2
,test
等模塊。引入
maven
依賴
<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>
- 以一個(gè)
Person
模型的查詢(query)為例,創(chuàng)建POJO
類Person
、數(shù)據(jù)訪問ContactDao
接口、服務(wù)ContactService
接口、以及對應(yīng)的Restful
服務(wù)控制器Controller
。其中,在Controller
中暴露3個(gè)Rest
服務(wù)接口:
@RestController
@RequestMapping("/")
public class ContactController {
@Autowired
private ContactService contactService;
@GetMapping("/test")
public String test() {
return "hello world";
}
@GetMapping("/persons")
public Iterable<Person> getAllPersons() {
return contactService.getAllContacts();
}
@GetMapping("/getPersonById")
public Person getPersonById(@RequestParam("id") int personId) {
return contactService.getContactById(personId);
}
-
/test
用來測試 -
/persons
查詢所有Person
對象 -
getPersonById
根據(jù)id
來查詢對應(yīng)的Person
- 配置
Swagger
使用注解@EnableSwagger2
來啟用相關(guān)功能。
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("io.github.ted005.swaggerdemo.controller"))
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
- 運(yùn)行查看
api doc
, 打開http://localhost:8080/swagger-ui.html
,會列出提供的api
接口。
Screenshot_2019-01-21 Swagger UI.png
而且,還可以對每一個(gè)接口進(jìn)行測試(可能需要構(gòu)造請求參數(shù)):
Screenshot_2019-01-21 Swagger UI(1).png