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 {
@Bean
public 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 {
@Autowired
MyConfig myconfig;
@RequestMapping("/info")
public String msg() {
return "client1 service"+myconfig.toString();
}
}
---
6.访问http://localhost:8071/swagger-ui.html 查看效果
+
end