您的位置:首页 > 编程语言 > Java开发

01.Spring Cloud学习笔记之使用IDEA+Spring Boot快速构建Rest服务

2017-08-26 20:57 946 查看

前言

写本系列博客的初衷有三:首先是希望能通过这种方式让自己对学习的知识点进行一个总结,待日后复习也有迹可循;其次是本着开放与人分享的心态,希望能帮助到正在学习Spring Cloud的朋友;最后是希望如果对某方面知识点有误解的地方能得到大神批评指教。本系列博客主要参考了Spring Cloud官方文档,以及周立老师的Spring Cloud教程和翟永超的Spring Cloud微服务实战,博客中阐述的所有观点仅代表个人观点,不喜勿喷

使用IDEA快速构建Spring Boot项目

在新建项目时选择Spring Initializr



填写项目基本信息



选择依赖模块



搭建完成项目结构如下图所示



注:新建的骨架项目会包含一些不必要的文件 自行删除即可

编写Hello World案例

新建HelloWorldController

package com.roberto.springboot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
@RequestMapping("/hello")
public String index(){
return "Hello World";
}
}


访问http://localhost:8080/hello查看结果



编写RESTful测试类

package com.roberto.springboot;

import com.roberto.springboot.controller.HelloController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringbootQuickStartApplicationTests {
private MockMvc mockMvc;

@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}

@Test
public void testHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Hello World"));
}
}


andExpect是添加ResultMatcher验证规则 验证控制器执行完成后结果是否正确

JSONView插件

浏览器访问RESTful接口时返回一段JSON字符串,但是在显示的时候没有进行格式化,密密麻麻看的眼花缭乱。通常有人是复制结果下来再去第三方进行解析格式化,其实Chrome提供了一款非常实用的插件JSONView,只需要去谷歌商店下载并且启用即可

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐