1. 程式人生 > >Spring Boot 入門之基礎篇(一)

Spring Boot 入門之基礎篇(一)

一、前言

Spring Boot 是由 Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring 應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。

本系列以快速入門為主,可當作工具小手冊閱讀

二、環境搭建

建立一個 maven 工程,目錄結構如下圖:

image

2.1 新增依賴

建立 maven 工程,在 pom.xml 檔案中新增如下依賴:

<!-- 定義公共資源版本 -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<
artifactId
>
spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath /> </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> <!-- 上邊引入 parent,因此 下邊無需指定版本 --> <!-- 包含 mvc,aop 等jar資源 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId
>
</dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

2.2 建立目錄和配置檔案

建立 src/main/resources 原始檔目錄,並在該目錄下建立 application.properties 檔案、static 和 templates 的資料夾。

application.properties:用於配置專案執行所需的配置資料。

static:用於存放靜態資源,如:css、js、圖片等。

templates:用於存放模板檔案。

目錄結構如下:

image

2.3 建立啟動類

在 com.light.springboot 包下建立啟動類,如下:

/**
 該註解指定專案為springboot,由此類當作程式入口
 自動裝配 web 依賴的環境
 
**/
@SpringBootApplication
public class SpringbootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}
}

2.4 案例演示

建立 com.light.springboot.controller 包,在該包下建立一個 Controller 類,如下:

@RestController
public class TestController {

	@GetMapping("/helloworld")
	public String helloworld() {
		return "helloworld";
	}
}

在 SpringbootApplication 檔案中右鍵 Run as -> Java Application。當看到 “Tomcat started on port(s): 8080 (http)” 字樣說明啟動成功。

image

讀者可以使用 STS 開發工具,裡邊集成了外掛,可以直接建立 Spingboot 專案,它會自動生成必要的目錄結構。

三、熱部署

當我們修改檔案和建立檔案時,都需要重新啟動專案。這樣頻繁的操作很浪費時間,配置熱部署可以讓專案自動載入變化的檔案,省去的手動操作。

在 pom.xml 檔案中新增如下配置:

<!-- 熱部署 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<optional>true</optional>
	<scope>true</scope>
</dependency>
<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<!-- 沒有該配置,devtools 不生效 -->
				<fork>true</fork>
			</configuration>
		</plugin>
	</plugins>
</build>

配置好 pom.xml 檔案後,我們啟動專案,隨便建立/修改一個檔案並儲存,會發現控制檯列印 springboot 重新載入檔案的資訊。

演示圖如下:

image

四、多環境切換

application.properties 是 springboot 在執行中所需要的配置資訊。

當我們在開發階段,使用自己的機器開發,測試的時候需要用的測試伺服器測試,上線時使用正式環境的伺服器。

這三種環境需要的配置資訊都不一樣,當我們切換環境執行專案時,需要手動的修改多出配置資訊,非常容易出錯。

為了解決上述問題,springboot 提供多環境配置的機制,讓開發者非常容易的根據需求而切換不同的配置環境。

在 src/main/resources 目錄下建立三個配置檔案:

application-dev.properties:用於開發環境
application-test.properties:用於測試環境
application-prod.properties:用於生產環境

我們可以在這個三個配置檔案中設定不同的資訊,application.properties 配置公共的資訊。

在 application.properties 中配置:

spring.profiles.active=dev

表示啟用 application-dev.properties 檔案配置, springboot 會載入使用 application.properties 和 application-dev.properties 配置檔案的資訊。

同理,可將 spring.profiles.active 的值修改成 test 或 prod 達到切換環境的目的。

演示圖如下:

image

五、配置日誌

5.1 配置 logback(官方推薦使用)

5.1.1 配置日誌檔案

spring boot 預設會載入 classpath:logback-spring.xml 或者 classpath:logback-spring.groovy。

如需要自定義檔名稱,在 application.properties 中配置 logging.config 選項即可。

在 src/main/resources 下建立 logback-spring.xml 檔案,內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 檔案輸出格式 -->
    <property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
    <!-- test檔案路徑 -->
    <property name="TEST_FILE_PATH" value="d:/test.log" />
    <!-- pro檔案路徑 -->
    <property name="PRO_FILE_PATH" value="/opt/test/log" />
    
    <!-- 開發環境 -->
    <springProfile name="dev">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>${PATTERN}</pattern>
            </encoder>
        </appender>
        <logger name="com.light.springboot" level="debug" />
        <root level="info">
            <appender-ref ref="CONSOLE" />
        </root>
    </springProfile>
    
    <!-- 測試環境 -->
    <springProfile name="test">
        <!-- 每天產生一個檔案 -->
        <appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 檔案路徑 -->
            <file>${TEST_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 檔名稱 -->
                <fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
                <!-- 檔案最大儲存歷史數量 -->
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>
        <root level="info">
            <appender-ref ref="TEST-FILE" />
        </root>
    </springProfile>
    
    <!-- 生產環境 -->
    <springProfile name="prod">
        <appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${PRO_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
                <MaxHistory>100</MaxHistory>
            </rollingPolicy>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${PATTERN}</pattern>
            </layout>
        </appender>
        <root level="warn">
            <appender-ref ref="PROD_FILE" />
        </root>
    </springProfile>
</configuration>

其中,springProfile 標籤的 name 屬性對應 application.properties 中的 spring.profiles.active 的配置。

即 spring.profiles.active 的值可以看作是日誌配置檔案中對應的 springProfile 是否生效的開關。

5.2 配置 log4j2

5.2.1 新增依賴

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

5.2.2 配置日誌檔案

spring boot 預設會載入 classpath:log4j2.xml 或者 classpath:log4j2-spring.xml。

如需要自定義檔名稱,在 application.properties 中配置 logging.config 選項即可。

log4j2.xml 檔案內容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <properties>
        <!-- 檔案輸出格式 -->
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
    </properties>
    <appenders>
        <Console name="CONSOLE" target="system_out">
            <PatternLayout pattern="${PATTERN}" />
        </Console>
    </appenders>
    <loggers>
        <logger name="com.light.springboot" level="debug" />
        <root level="info">
            <appenderref ref="CONSOLE" />
        </root>
    </loggers>
</configuration>

log4j2 不能像 logback 那樣在一個檔案中設定多個環境的配置資料,只能命名 3 個不同名的日誌檔案,分別在 application-dev,application-test 和 application-prod 中配置 logging.config 選項。

除了在日誌配置檔案中設定引數之外,還可以在 application-*.properties 中設定,日誌相關的配置:

logging.config                    # 日誌配置檔案路徑,如 classpath:logback-spring.xml
logging.exception-conversion-word # 記錄異常時使用的轉換詞
logging.file                      # 記錄日誌的檔名稱,如:test.log
logging.level.*                   # 日誌對映,如:logging.level.root=WARN,logging.level.org.springframework.web=DEBUG
logging.path                      # 記錄日誌的檔案路徑,如:d:/
logging.pattern.console           # 向控制檯輸出的日誌格式,只支援預設的 logback 設定。
logging.pattern.file              # 向記錄日誌檔案輸出的日誌格式,只支援預設的 logback 設定。
logging.pattern.level             # 用於呈現日誌級別的格式,只支援預設的 logback 設定。
logging.register-shutdown-hook    # 初始化時為日誌系統註冊一個關閉鉤子

六、打包執行

打包的形式有兩種:jar 和 war。

6.1 打包成可執行的 jar 包

預設情況下,通過 maven 執行 package 命令後,會生成 jar 包,且該 jar 包會內建了 tomcat 容器,因此我們可以通過 java -jar 就可以執行專案,如下圖:

image

6.2 打包成部署的 war 包

讓 SpringbootApplication 類繼承 SpringBootServletInitializer 並重寫 configure 方法,如下:

@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootApplication.class);
    }

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}
}

修改 pom.xml 檔案,將 jar 改成 war,如下:

<packaging>war</packaging>

打包成功後,將 war 包部署到 tomcat 容器中執行即可。

七、參考資料