标签:start pid mcr from 运行 资源 应用程序 art eset
构建 Maven 项目
工程结构解析
如上图所示,Spring Boot 的基础结构有三大块(具体路径根据用户生成项目时填写的Group和Artifact有所差异)
Maven配置分析
打开当前工程下的 pom.xml 文件,可以看到如下关键配置:
????????<parent>
????????????????<groupId>org.springframework.boot</groupId>
????????????????<artifactId>spring-boot-starter-parent</artifactId>
????????????????<version>1.5.4.RELEASE</version>
????????????????<relativePath/> <!-- lookup parent from repository -->
????????</parent>
????????<properties>
????????????????<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
????????????????<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
????????????????<java.version>1.8</java.version>
????????</properties>
????????<dependencies>
????????????????<dependency>
????????????????????????<groupId>org.springframework.boot</groupId>
????????????????????????<artifactId>spring-boot-starter-web</artifactId>
????????????????</dependency>
? ?
????????????????<dependency>
????????????????????????<groupId>org.springframework.boot</groupId>
????????????????????????<artifactId>spring-boot-starter-test</artifactId>
????????????????????????<scope>test</scope>
????????????????</dependency>
????????</dependencies>
实现 RESTful API
在Spring Boot 中创建一个RESTFul API 的实现代码同 Spring MVC一样,只是不需要Spring MVC那样先做很多配置,步骤如下:
@RestController
public class HelloController {
????????@RequestMapping ("/hello")
????????public String index() {
????????????????return "Hello World";
????????}
}
启动 Spring Boot 应用
启动 Spring Boot 应用的方式很多种:
编写单元测试
在Spring Boot 中实现单元测试很方便,我们打开 src/test 下的单元测试入口 SpringbootDemoApplicationTests 类,编写一个简单的单元测试来模拟 HTTP 请求,测试代码如下:
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.setup.MockMvcBuilders;
? ?
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
? ?
@RunWith (SpringRunner.class)
@SpringBootTest
public class SpringbootDemoApplicationTests {
? ?
????????private MockMvc mvc;
? ?
????????@Before
????????public void setUp() {
????????????????mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
????????}
? ?
????????@Test
????????public void helloTest() throws Exception {
????????????????mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON_UTF8))
????????????????????????????????.andExpect(status().isOk())
????????????????????????????????.andExpect(content().string("Hello World"));
????????}
? ?
}
代码解析如下:
? ?
? ?
标签:start pid mcr from 运行 资源 应用程序 art eset
原文地址:http://www.cnblogs.com/li3807/p/7203455.html