注意:本 Spring Boot 系列文章基於 Spring Boot 版本 v2.1.1.RELEASE 進行學習分析,版本不一樣可能會有細微差異。
因爲 J2EE 的開發變得笨重,繁多的配置,錯亂的依賴管理,低下的開發效率,複雜的部署流程,第三方技術的集成難度較大等。同時隨着複雜項目的演進,微服務分佈式架構思想逐漸進入開發者的視野。java
Spring Boot
提供了一組工具只須要極少的配置就能夠快速的構建並啓動基於 Spring 的應用程序。解決了傳統 Spring 開發須要配置大量配置文件的痛點,同時 Spring Boot
對於第三方庫設置了合理的默認值,能夠快速的構建起應用程序。固然 Spring Boot
也能夠輕鬆的自定義各類配置,不管是在開發的初始階段仍是投入生成的後期階段。git
<!-- more -->github
說了那麼多的 Spring Boot 的好處,那麼使用 Spring Boot 須要哪些前置知識呢?我簡單列舉了一下。web
如今咱們已經瞭解了 Spring Boot 是什麼,下面咱們將使用 Spring Boot 開發一個入門案例,來體驗 Spring Boot 開發姿式是如何的優雅與迅速。
Spring Boot 官方已經爲咱們如何快速啓動 Spring Boot 應用程序提供了多種方式。面試
你能夠在 Spring 官方網站直接生成項目下載導入IDE進行開發。spring
https://start.spring.io/
也能夠直接克隆 GitHub 上的初始項目進行體驗。shell
git clone https://github.com/spring-guides/gs-spring-boot.git cd gs-spring-boot/initial
這裏咱們選擇後者,直接克隆進入到 initial 文件夾使用 maven 進行編譯啓動。springboot
mvn package && java -jar target/gs-spring-boot-0.1.0.jar
第一次編譯須要下載須要的依賴,耗時會比較長,編譯完成以後緊接着能夠看到 Spring 的啓動標誌。這時 Spring Boot 的 web程序已經運行在8080端口了。服務器
$ curl -s localhost:8080 Greetings from Spring Boot!
下面手動編寫一個 Spring Boot 入門案例,快速的開發一個 web mvc 應用。
項目結構以下:架構
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <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> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
spring-boot-starter-parent
是Spring Boot 的核心依賴,它裏面定義了各類在開發中會用到的第三方 jar 的版本信息,所以咱們在引入其餘的 Spring Boot 爲咱們封裝的啓動器的時候都不在須要指定版本信息。若是咱們須要自定義版本信息,能夠直接覆蓋版本屬性值便可。
spring-boot-starter-web
提供 web 以及 MVC 和 validator 等web開發框架的支持。
spring-boot-starter-test
提供測試模塊的支持。如 Junit,Mockito。
須要說明的是,Spring Boot 爲咱們提供了不少的已經封裝好的稱爲啓動器(starter)的依賴項。讓咱們在使用的時候不須要再進行復雜的配置就能夠迅速的進行應用集成。全部的官方啓動器依賴能夠在這裏查看。
全部 官方發佈的啓動器都遵循相似的命名模式;spring-boot-starter-*
,這裏*
是指特定類型的應用程序。此命名結構旨在幫助您尋找啓動器。注意:編寫本身的啓動器的時候不該該使用這種命名方式。
@SpringBootApplication public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return args -> { // 開始檢查spring boot 提供的 beans System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } }; } }
@SpringBootApplication
註解是一個便利的註解,它包含了如下幾個註解。
@Configuration
定義配置類。@EnableAutoConfiguration
開啓自動配置。@EnableWebMvc
標記爲 web應用程序。@ComponentScan
組件掃描。@RestController public class HelloController { @RequestMapping("/") public String index() { return "Greetings from Spring Boot!"; } }
@RestController
是 @Controller
與 @ResponseBody
的結合體。
直接啓動 HelloApplication.java
類就能夠在控制檯看到啓動輸出,而後訪問8080端口查看啓動是否正常。
通過上面的例子,已經使用 Spring Boot 快速的建立了一個 web 應用並進行了簡單的訪問測試。
結合上面提到的 Spring Boot 啓動器知識,Spring Boot 已經爲咱們提供了豐富的第三方框架,測試框架也不例外。
導入單元測試依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
編寫單元測試
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.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * 單元測試 */ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class HelloApplicationTests { @Autowired private MockMvc mvc; @Test public void contextLoads() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("Greetings from Spring Boot!")); } }
關於上面代碼的一些說明。
運行沒有任何異常說明程序測試經過。
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import java.net.URL; /** * <p> * 嵌入式服務器由隨機端口啓動webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT * 而且在運行時發現實際端口@LocalServerPort * * @Author niujinpeng * @Date 2018/12/4 15:02 */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloApplicationTestBySpringBoot { @LocalServerPort private int port; private URL base; @Autowired private TestRestTemplate template; @Before public void setup() throws Exception { this.base = new URL("http://localhost:" + port + "/"); } @Test public void getHello() throws Exception { ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); assert (response.getBody().equals("Greetings from Spring Boot!")); } }
嵌入式服務器由隨機端口啓動 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
而且在運行時使用註解 @LocalServerPort
發現實際端口。
運行測試類經過輸出。
2018-12-06 22:28:01.914 INFO 14320 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2018-12-06 22:28:01.914 INFO 14320 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2018-12-06 22:28:01.937 INFO 14320 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 23 ms
文章代碼已經上傳到 GitHub Spring Boot 入門案例。
<完>
我的網站:https://www.codingme.net
若是你喜歡這篇文章,能夠關注公衆號,一塊兒成長。
關注公衆號回覆資源能夠沒有套路的獲取全網最火的的 Java 核心知識整理&面試資料。