博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《Spring Boot系列》- Swagger2构建RESTful API文档
阅读量:5783 次
发布时间:2019-06-18

本文共 5267 字,大约阅读时间需要 17 分钟。

hot3.png

项目结构

192915_meyv_2330610.png

引入依赖

apply plugin:'java'repositories{	maven{		url 'http://maven.aliyun.com/nexus/content/groups/public/'	}}dependencies{	compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.4.2.RELEASE'    compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.4.2.RELEASE'    compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'    compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'}

用户类

public class User {	private Long id;	private String name;	private Integer age;

控制器类

@RestController@RequestMapping(value = "/users")public class UserController {	static Map
users = Collections.synchronizedMap(new HashMap
()); @ApiOperation(value = "获取用户列表", notes = "") @RequestMapping(value = "/", method = RequestMethod.GET) public List
getUserList() { // 获取列表 List
list = new ArrayList
(users.values()); return list; } @ApiOperation(value = "创建用户", notes = "根据User对象创建用户") @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") @RequestMapping(value = "/", method = RequestMethod.POST) public String postUser(@ModelAttribute User user) { // 添加user users.put(user.getId(), user); return "success"; } @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUesr(@PathVariable Long id) { // 获取单个实体 return users.get(id); } @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path"), @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") }) @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // 修改实体 User item = users.get(id); item.setName(user.getName()); item.setAge(user.getAge()); users.put(id, item); return "success"; } @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 删除单个实体 users.remove(id); return "success"; }}

Swagger2类

@Configuration@EnableSwagger2public class Swagger2 {	@Bean	public Docket createRestApi() {		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()				.apis(RequestHandlerSelectors.basePackage("com.kimisme.web")).paths(PathSelectors.any()).build();	}	private ApiInfo apiInfo() {		return new ApiInfoBuilder().title("Spring Boot中使用Swagger2构建RESTful APIs")				.description("在网页中输入http://localhost:8080/swagger-ui.html会看到惊喜")				.termsOfServiceUrl("http://kimisme.com/").contact("绝影").version("1.0").build();	}}

测试类

import static org.hamcrest.Matchers.equalTo;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = MockServletContext.class)@WebAppConfigurationpublic class ApplicationTests {	private MockMvc mvc;	@Before	public void setUp() {		mvc = MockMvcBuilders.standaloneSetup(new HelloController(), new UserController()).build();	}	@Test	public void getHello() throws Exception {		mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())				.andExpect(content().string(equalTo("Hello World")));	}	@Test	public void testUserController() throws Exception {		RequestBuilder request = null;		// 1.0 get获取user列表,返回空		request = get("/users/");		mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));		// 2.0 post添加一个user		request = post("/users/").param("id", "1").param("name", "Tony").param("age", "20");		mvc.perform(request)				// .andDo(MockMvcResultHandlers.print())//打印本次请求详情				.andExpect(content().string(equalTo("success")));		// 3.0 get查询列表,返回刚插入的数据		request = get("/users/");		mvc.perform(request).andExpect(status().isOk())				.andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"Tony\",\"age\":20}]")));		// 4.0 put修改id为1的user		request = put("/users/1").param("name", "Lily").param("age", "18");		mvc.perform(request).andExpect(content().string(equalTo("success")));		// 5.0 get获取id为1的user		request = get("/users/1");		mvc.perform(request).andExpect(content().string(equalTo("{\"id\":1,\"name\":\"Lily\",\"age\":18}")));		// 6.0 del删除id为1的user		request = delete("/users/1");		mvc.perform(request).andExpect(content().string(equalTo("success")));		// 7、get获取user列表,返回空		request = get("/users/");		mvc.perform(request).andExpect(status().isOk()).andExpect(content().string(equalTo("[]")));	}}

测试

在浏览器输入http://localhost:8080/swagger-ui.html

参考资料

转载于:https://my.oschina.net/kimisme/blog/1595775

你可能感兴趣的文章
JBPM之JPdl小叙
查看>>
(step6.1.5)hdu 1233(还是畅通工程——最小生成树)
查看>>
Membership三步曲之进阶篇 - 深入剖析Provider Model
查看>>
前端优化及相关要点总结
查看>>
struts2中form提交到action中的中文参数乱码问题解决办法(包括取中文路径)
查看>>
25 个精美的手机网站模板
查看>>
C#反射实例应用--------获取程序集信息和通过类名创建类实例
查看>>
VC中实现文字竖排的简单方法
查看>>
会话标识未更新
查看>>
阿里架构师:程序员必须掌握的几项核心技术能力
查看>>
程序员常用的六大技术博客类
查看>>
Iceworks 2.8.0 发布,自定义你的 React 模板
查看>>
胖哥学SpringMVC:请求方式转换过滤器配置
查看>>
Kotlin 更加优雅的 Builder - 理解 with
查看>>
前端日拱一卒D6——字符编码与浏览器解析
查看>>
深入理解浏览器的缓存机制
查看>>
微软向Linux社区开放60000多项专利:对开源微软是认真的
查看>>
Hoshin Kanri在丰田的应用
查看>>
又拍云沈志华:如何打造一款安全的App
查看>>
克服大数据集群的挑战
查看>>