构建项目
在idea中选择新建spring initializer项目。生成如图所示的目录结构。
B5DA67AB-7D96-4FE1-BD53-CCC975FF7C3D.png
src/main/java:源代码目录,主程序入口Application,可通过该类启动springboot应用。spring自动扫描启动类所在层级及其子层级的类。
src/main/resource:配置目录,该目录用于存放应用的配置信息,如应用名、服务端口、数据库链接等。由于我们引入了web模块,因此产生了static、templates目录,前者用于存放静态资源,如图片、css、js,后者用于存放web页面的模版文件。
src/main/test:单元测试目录,存放测试文件。
实现Restful API
在Springboot中创建一个Restful Api的实现代码同Spring MVC应用一样,只是不需要像Spring Mvc那样先做很多配置,而是像下面这样直接编写Controller内容。
package com.example.springboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String sayHello() {
return "hello world";
}
}
实现Restful API
功能实现之后,我们要养成随手写单元测试的习惯。在springboot中实现单元测试同样方便。我们应该在test目录下新建HelloWorldControllerTest类,测试之前的/hello接口,该接口应该返回 hello world字符串。
package com.example.springboot.controller;
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.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HelloWorldController.class)
public class HelloWorldControllerTest {
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
}
@Test
public void sayHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("hello world"));
}
}
代码解析如下:
@RunWith(SpringJUnit4ClassRunner.class):引入springboot对junit的支持。
@SpringBootTest(classes = HelloWorldController.class):指定springboot的启动类,值得一提的是,在springboot2.0之后,@SpringBootTest替换了原来的@SpringApplicationConfiguration注解。
@WebAppConfiguration:开启web应用的配置,用于模拟ServletContext。
mockMvc对象:用于模拟调用Controller的接口发起请求,在@Test定义的hello测试用例中,perform函数执行一次函数调用,accept用于执行接收的数据类型,andExcept用于判断接口返回的期望值。
@Before:junit中定义在测试用例@Test内容执行之前预加载的内容。
网友评论