Spring Boot 是由Pivotal團(tuán)隊(duì)提供的全新框架恐疲,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置衔瓮,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力于在蓬勃發(fā)展的快速應(yīng)用開發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者姥饰。
下面,我們先做個(gè)簡單的樣例:
一孝治、新建項(xiàng)目
新建maven項(xiàng)目springboot-bucket-mine
列粪,然后再其下新建module springboot-base
,建完后目錄如下圖所示
項(xiàng)目搭建 1
二谈飒、引入依賴
-
打開springboot官網(wǎng)https://projects.spring.io/spring-boot岂座,點(diǎn)擊
QUICK START
,可以看到如下圖所示
項(xiàng)目搭建 2 如上圖所示杭措,我們在父pom.xml中加入如下代碼
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
- 在子pom.xml加入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
三费什、新建restController
代碼如下
package com.springboot.my.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/")
public String index(){
return "Greetings from Spring Boot!";
}
}
四、新建啟動類
代碼如下
package com.springboot.my;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class, args);
}
}
五手素、啟動&驗(yàn)證
執(zhí)行BaseApplication.java
中的main方法鸳址,控制臺啟動日志和接口驗(yàn)證如下
啟動
接口驗(yàn)證
五瘩蚪、Junit Test
- 新增依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 編寫測試代碼
package com.springboot.my;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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 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(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void helloTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}