構建 Maven 項目 java
工程結構解析 web
如上圖所示,Spring Boot 的基礎結構有三大塊(具體路徑根據用戶生成項目時填寫的Group和Artifact有所差別) spring
Maven配置分析 數據庫
打開當前工程下的 pom.xml 文件,能夠看到以下關鍵配置: 服務器
<parent>mvc
<groupId>org.springframework.boot</groupId>app
<artifactId>spring-boot-starter-parent</artifactId>函數
<version>1.5.4.RELEASE</version>spring-boot
<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"));
}
}
代碼解析以下: