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

Spring Boot 學習之基礎篇(一)

該系列並非完全原創,官方文件作者

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

一、環境搭建

建立一個Maven專案,結構如圖,檔案目錄可忽略。如何建立Maven專案


1、新增依賴

在 pom.xml 檔案中新增如下依賴

<!-- 定義公共資源版本 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.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、建立目錄和配置檔案

在resources 原始檔目錄,建立 application.properties 檔案、static 和 templates 的資料夾。
application.properties:用於配置專案執行所需的配置資料。
static:用於存放靜態資源,如:css、js、圖片等。

templates:用於存放模板檔案。

3、建立啟動類

在src根目錄下建立,一定要在根目錄,看原始碼預設掃描此類所在包下的所有註解。

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

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

4、啟動專案

在 SpringbootApplication 檔案中右鍵 Run as -> Java Application。圖就不上了

二、熱部署

pom.xml修改並新增

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<scope>runtime</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>

ctrl+s儲存後,再啟動專案,隨便建立/修改一個檔案並儲存,會發現控制檯列印 springboot 重新載入檔案的資訊。

三、多環境

如初圖,按照我在SGM的開發規則,application.properties 是 springboot 在執行中所需要的配置資訊。
當我們在開發階段,本地機器開發,測試的時候用測試伺服器測試,上線時使用正式環境的伺服器。
這三種環境需要的配置資訊都不一樣,當切換環境執行專案時,需要手動的修改多出配置資訊,非常容易出錯。
為了解決上述問題,springboot 提供多環境配置的機制,讓開發者非常容易的根據需求而切換不同的配置環境。
在 src/main/resources 目錄下建立三個配置檔案:
application-local.properties:用於本地環境
application-qa.properties:用於測試環境
application-prod.properties:用於生產環境

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

在 application.properties 中配置:

spring.profiles.active=local

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

在application-local.properties配置加上

server.port = 8081

再重新啟動專案發現只能用8081埠訪問了(如果被佔用會報錯的,再修改)

四、配置日誌

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" />
    <!-- local檔案路徑 -->
    <property name="LOCAL_FILE_PATH" value="E:/Eclipse/workspace/sgm/phil-springboot/log" />
    <!-- pro檔案路徑 -->
    <property name="PRO_FILE_PATH" value="/midware/logfiles" />
    
     <!-- 本地環境 -->
    <springProfile name="local">
        <!-- 每天產生一個檔案 -->
        <appender name="LOCAL_FILE_PATH" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <!-- 檔案路徑 -->
            <file>${LOCAL_FILE_PATH}</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <!-- 檔名稱 -->
                <fileNamePattern>${LOCAL_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="LOCAL_FILE_PATH" />
        </root>
    </springProfile>
    
    <!-- 測試環境 -->
    <springProfile name="qa">
        <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>${PATTERN}</pattern>
            </encoder>
        </appender>
        <logger name="com.phil.springboot" level="debug"/>
        <root level="info">
            <appender-ref ref="CONSOLE" />
        </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>

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

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

2、配置 log4j2

新增並修改依賴

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

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>

配置日誌檔案

pring 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.phil.springboot" level="debug"/>
        <root level="info"><!-- 預設是debug -->
            <appenderref ref="CONSOLE" />
        </root>
    </loggers>
</configuration>
log4j2 不能像 logback 那樣在一個檔案中設定多個環境的配置資料,只能命名 3 個不同名的日誌檔案,分別在 application-local,application-qa和 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    # 初始化時為日誌系統註冊一個關閉鉤子

五、常用註解

@Configuration                 # 作用於類上,相當於一個 xml 配置檔案
@Bean                          # 作用於方法上,相當於 xml 配置中的 <bean>
@SpringBootApplication         # Spring Boot的核心註解,是一個組合註解,用於啟動類上
@EnableAutoConfiguration       # 啟用自動配置,允許載入第三方 Jar 包的配置
@ComponentScan                 # 預設掃描 @SpringBootApplication 所在類的同級目錄以及它的子目錄
@PropertySource                # 載入 properties 檔案
@Value                         # 將配置檔案的屬性注入到 Bean 中特定的成員變數
@EnableConfigurationProperties # 開啟一個特性,讓配置檔案的屬性可以注入到 Bean 中,與 @ConfigurationProperties 結合使用
@ConfigurationProperties       # 關聯配置檔案中的屬性到 Bean 中
@Import                        # 載入指定 Class 檔案,其生命週期被 Spring 管理
@ImportResource                # 載入 xml 檔案

六、讀取配置檔案

1、屬性裝配

有兩種方式:使用 @Value 註解和 Environment 物件。

在application-local.properties 中新增如下自定義配置

userName=root
password=root

建立配置類如下

package com.phil.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class EnvironmentValueConfig {

	@Value("${userName}")
	private String userName;
	@Autowired
	private Environment environment;

	public void show() {
		System.out.println("userName:" + this.userName);
		System.out.println("password:" + this.environment.getProperty("password"));
	}
}

通過 @Value 獲取 userName 配置;通過 environment 獲取 password 配置。

修改SpringbootApplication啟動類的main方法

ConfigurableApplicationContext context = SpringApplication.run(SpringbootApplication.class, args);
context.getBean(EnvironmentValueConfig.class).show();

2、物件裝配

修改下配置

phil.userName=root
phil.password=root

建立需要裝配的物件

package com.phil.springboot.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "phil")
public class EnvironmentValueProperties {

	private String userName;

	private String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void show() {
		System.out.println("phil.userName=" + this.userName);
		System.out.println("phil.password=" + this.password);
	}
}

如果此處出現Warnning,在pom.xml加上如下

dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

重新啟動