1、下载项目压缩包
点击如图按钮即可下载。下载地址【传送门】
2、解压,打开IDE,以maven项目导入。
3、在pom中引入web模块
导入的项目中pom.xml里,默认只引入了:
- spring-boot-starter:核心模块,包括自动配置支持、日志和YAML
- spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockit
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
4、HelloWorld
新建包com.example.demo.web,创建HelloController类
package com.example.demo.web;
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";
}
}
5、启动DemoApplication.java
访问http://localhost:8080/hello
6、在测试入口编写测试类模拟http请求
package com.example.demo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
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 com.example.demo.web.HelloController;
import static org.hamcrest.Matchers.equalTo;
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)
@WebAppConfiguration
public class DemoApplicationTests {
private MockMvc mvc;
@Before
public void setUp()throws Exception
{
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).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")));
}
}
总结:
通过Maven构建了一个空白Spring Boot项目,再通过引入web模块实现了一个简单的请求处理。附上本文学习引用的原文链接:http://mp.weixin.qq.com/s/6S1bvsD7wXu71T7qWGJQ_Q