SpringBoot入門之零基礎搭建web應用
引言
之前也沒有深入學習過spring框架,最近SpringBoot流行起來後想補下這方面的知識,於是照著SpringBoot官網上的英文教程開始helloworld入門,踩到幾個小坑,記錄下學習流程。
SpringBoot有哪些優點
SpringBoot可以幫助我們快速搭建應用,自動裝配缺失的bean,使我們把更多的精力集中在業務開發上而不是基礎框架的搭建上。它有但是遠不止以下這幾點優點:
- 它有內建的Tomcat和jetty容器,避免了配置容器、部署war包等步驟
- 能夠自動新增缺失的bean
- 簡化了xml配置甚至不需要xml來配置bean
入門準備工作
- JDK1.8+(JDK1.7也可以,但是官方的例程裡用到了一些lambda表示式,lambda表示式只在JDK1.8及以上的版本才支援)
- MAVEN 3.0+
- IDE:IDEA (開發工具我選擇的是IDEA)
搭建HelloWorld web應用
建立一個空maven工程
使用idea建立maven工程,這裡GroupId和artifactId任意指定即可
我們開始配置pom檔案,指定該helloworld的父工程為spring-boot-starter-parent,這樣我們就不需要指定SpringBoot的一些相關依賴的版本了(因為在父工程中已指定)。
配置完的pom.xml檔案如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId >helloworld</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
其中spring-boot-maven-plugin外掛可以幫助我們在使用mvn package
命令打包的時候生成一個可以直接執行的jar檔案。(spring-boot-maven-plugin作用)
建立web應用
建立一個controller,目錄在src/main/java/hello/HelloController.java
package hello;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zengrong.gzr
* @Date 2017/03/11
*/
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
@RequestMapping("/HelloWorld")
public String hello() {
return "Hello World!";
}
}
建立一個web application,目錄在src/main/java/hello/HelloController.java
package hello;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
/**
* @author zengrong.gzr
* @Date 2017/03/11
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//指定下bean的名稱
@Bean(name = "gzr")
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
for (String beanName : beanNames){
System.out.println(beanName);
}
}
};
}
}
可以看到,我們不需要xml來配置bean,也不需要配置web.xml檔案,這是一個純java應用,我們不需要來處理複雜的配置關係等。
執行應用
可以通過命令列直接執行應用
$ mvn package && java -jar target/helloworld-1.0-SNAPSHOT.jar
當然我更傾向於使用idea來執行,這樣可以debug看到SpringBoot的初始化過程,配置過程如下
讓我們用idea來debug看看,如果編譯時出現“Error:java: Compilation failed: internal java compiler error”的錯誤(如下圖),我們需要修改idea預設的編譯器設定
修改compiler設定如下
我們可以在控制檯看到執行結果,擷取一段見下圖,可以看到打印出的bean,包括helloController、和我們指定名字的gzr等
下面我們來檢查web的服務,在命令列執行
$ curl localhost:8080
Greetings from Spring Boot!
$ curl localhost:8080/HelloWorld
Hello World!%
服務正常執行~
新增測試用例
我們先在pom中新增測試需要的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
新增一個簡單的測試用例,目錄在src/test/java/hello/HelloControllerTest.java
package hello;
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;
/**
* @author zengrong.gzr
* @Date 2017/03/11
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}
可以很輕鬆地直接執行該test
至此我們模擬了http請求來進行測試,通過SpringBoot我們也可以編寫一個簡單的全棧整合測試:
src/test/java/hello/HelloControllerIT.java
package hello;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* @author zengrong.gzr
* @Date 2017/03/11
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
@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);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
通過webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
我們可以讓內建的伺服器在隨機埠啟動。
新增生產管理服務
通常我們在建設網站的時候,可能需要新增一些管理服務。SpringBoot提供了幾個開箱即用的管理服務,如健康檢查、dump資料等。
我們首先在pom中新增管理服務需要的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
直接執行程式,可以看到控制檯輸出諸多SpringBoot提供的管理服務
我們可以很方便地檢查app的健康狀況
$ curl localhost:8080/health
{"status":"UP"}
$ curl localhost:8080/dump
{"timestamp":1489226509796,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource.","path":"/dump"}
當我們執行curl localhost:8080/dump
可以看到返回狀態為“Unauthorized”,dump、bean等許可權需要關閉安全控制才可以訪問。那麼如何關閉?可以通過註解的方式,也可以通過配置application.properties的方式。
這裡我們選擇第二種,在src/main/resources
資料夾下新建application.properties檔案(框架會自動掃描該檔案),在檔案中添如配置management.security.enabled=false
即可。
啟動應用後,我們再執行curl localhost:8080/beans
命令,可以看到命令列打印出系統載入的所有bean。