SpringBoot入門之零基礎(chǔ)搭建web應用

引言

之前也沒有深入學習過spring框架,最近SpringBoot流行起來后想補下這方面的知識,于是照著SpringBoot官網(wǎng)上的英文教程開始helloworld入門,踩到幾個小坑,記錄下學習流程。

SpringBoot有哪些優(yōu)點

SpringBoot可以幫助我們快速搭建應用,自動裝配缺失的bean,使我們把更多的精力集中在業(yè)務開發(fā)上而不是基礎(chǔ)框架的搭建上。它有但是遠不止以下這幾點優(yōu)點:

  • 它有內(nèi)置的Tomcat和jetty容器,避免了配置容器、部署war包等步驟
  • 能夠自動添加缺失的bean
  • 簡化了xml配置甚至不需要xml來配置bean

入門準備工作

  • JDK1.8+(JDK1.7也可以,但是官方的例程里用到了一些lambda表達式,lambda表達式只在JDK1.8及以上的版本才支持)
  • MAVEN 3.0+
  • IDE:IDEA (開發(fā)工具我選擇的是IDEA)

搭建HelloWorld web應用

創(chuàng)建一個空maven工程

使用idea創(chuàng)建maven工程,這里GroupId和artifactId任意指定即可

創(chuàng)建maven工程

我們開始配置pom文件,指定該helloworld的父工程為spring-boot-starter-parent,這樣我們就不需要指定SpringBoot的一些相關(guān)依賴的版本了(因為在父工程中已指定)。
配置完的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作用)

創(chuàng)建web應用

創(chuàng)建一個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!";
    }
}

創(chuàng)建一個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應用,我們不需要來處理復雜的配置關(guān)系等。

運行應用

可以通過命令行直接運行應用
$ mvn package && java -jar target/helloworld-1.0-SNAPSHOT.jar

當然我更傾向于使用idea來運行,這樣可以debug看到SpringBoot的初始化過程,配置過程如下


idea運行app

讓我們用idea來debug看看,如果編譯時出現(xiàn)“Error:java: Compilation failed: internal java compiler error”的錯誤(如下圖),我們需要修改idea默認的編譯器設(shè)置


compile錯誤.png

修改compiler設(shè)置如下
compiler修改

我們可以在控制臺看到運行結(jié)果,截取一段見下圖,可以看到打印出的bean,包括helloController、和我們指定名字的gzr等


打印出的bean.png

下面我們來檢查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我們可以讓內(nèi)置的服務器在隨機端口啟動。

添加生產(chǎn)管理服務

通常我們在建設(shè)網(wǎng)站的時候,可能需要添加一些管理服務。SpringBoot提供了幾個開箱即用的管理服務,如健康檢查、dump數(shù)據(jù)等。
我們首先在pom中添加管理服務需要的依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

直接運行程序,可以看到控制臺輸出諸多SpringBoot提供的管理服務


SpringBoot提供的管理服務.png

我們可以很方便地檢查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"}

當我們執(zhí)行curl localhost:8080/dump可以看到返回狀態(tài)為“Unauthorized”,dump、bean等權(quán)限需要關(guān)閉安全控制才可以訪問。那么如何關(guān)閉?可以通過注解的方式,也可以通過配置application.properties的方式。

這里我們選擇第二種,在src/main/resources文件夾下新建application.properties文件(框架會自動掃描該文件),在文件中添如配置management.security.enabled=false即可。

啟動應用后,我們再運行curl localhost:8080/beans命令,可以看到命令行打印出系統(tǒng)加載的所有bean。

源碼下載

附上源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容