Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目,实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,同时swagger-ui还可以测试spring restful风格的接口功能。其官方网站为:http://swagger.io/
项目环境:
- jdk1.8
- SpringBoot1.5.3
- swagger2
效果图
首先添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
将注解添加到WebConfiguration的类上。
@Configuration
@EnableSwagger2
public class WebConfiguration extends WebMvcConfigurerAdapter{
}
Springfox会和一组Docket协同工作,所以需要在类中定义为bean。
@SpringBootApplication
public class SpringbootSwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwaggerApplication.class, args);
}
@Bean
public Docket useApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(path -> path.startsWith("/api/"))
.build();
}
}
Controller层
简单的curd接口。
@RestController
@RequestMapping("/api")
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<UserInfo> findAll() {
return userInfoService.findAll();
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public UserInfo findOne(@PathVariable("id") String id) {
return userInfoService.findOne(id);
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public UserInfo createUserInfo(UserInfo userInfo) {
return userInfoService.save(userInfo);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public UserInfo updateUserInfo(@PathVariable("id") String id, UserInfo userInfo) {
return userInfoService.update(id, userInfo);
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable("id") String id) {
userInfoService.delete(id);
}
}
最简单的搭建方法到此结束,有兴趣的朋友的可以去浏览下官网