Spring Boot 集成Swagger2生成RESTful API文档
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot 集成Swagger2生成RESTful API文档
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Swagger2可以在寫代碼的同時生成對應的RESTful API文檔,方便開發人員參考,另外Swagger2也提供了強大的頁面測試功能來調試每個RESTful API。
使用Spring Boot可以方便的集成Swagger2
?
1.新建Spring Boot項目
2.添加swagger依賴
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.2.2</version> </dependency> <dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.2.2</version> </dependency>
---
3.創建swagger配置類
/*** Created by LG on 2017/8/3.** Spring Boot中使用Swagger2構建RESTful APIs說明文檔* 訪問http://localhost:8071/swagger-ui.html 查看效果*/ @Configuration @EnableSwagger2 public class Swagger2 {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.luangeng.controller")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("Spring Boot中使用Swagger2構建RESTful APIs說明文檔--title").description("Spring Boot中使用Swagger2構建RESTful APIs說明文檔--description").contact("Spring Boot中使用Swagger2構建RESTful APIs說明文檔--contact").version("1.0.1").build();}}
---
4.添加一個UserController.java類
@RestController @RequestMapping(value="/users") public class UserController {private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());@ApiOperation(value="獲取用戶列表", notes="獲取用戶列表")@RequestMapping(value="/", method= RequestMethod.GET)public List<User> getUserList() {List<User> r = new ArrayList<User>(users.values());return r;}@ApiOperation(value="創建用戶", notes="根據User對象創建用戶")@ApiImplicitParam(name = "user", value = "實體user", required = true, dataType = "User")@RequestMapping(value="/", method=RequestMethod.POST)public String postUser(@ModelAttribute User user) {users.put(user.getId(), user);return "success";}@RequestMapping(value="/{id}", method=RequestMethod.GET)public User getUser(@PathVariable Long id) {return users.get(id);}@RequestMapping(value="/{id}", method=RequestMethod.PUT)public String putUser(@PathVariable Long id, @ModelAttribute User user) {User u = users.get(id);u.setName(user.getName());u.setAge(user.getAge());users.put(id, u);return "success";}@RequestMapping(value="/{id}", method=RequestMethod.DELETE)public String deleteUser(@PathVariable Long id) {users.remove(id);return "success";}}
---
再增加一個InfoController.java類
@RestController public class InfoController {@AutowiredMyConfig myconfig;@RequestMapping("/info")public String msg() {return "client1 service"+myconfig.toString();}}
---
6.訪問http://localhost:8071/swagger-ui.html?查看效果
+
?
?
end
轉載于:https://www.cnblogs.com/luangeng/p/6130475.html
總結
以上是生活随笔為你收集整理的Spring Boot 集成Swagger2生成RESTful API文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个好听的杂志名字!
- 下一篇: IO流数据读写总结