javascript
springboot pom文件指定jdk_Spring Boot 入门
SpringBoot 基本應用
約定優于配置
約定優于配置(Convention over Configuration),又稱按約定編程,是一種軟件設計范式。
本質上是說,系統、類庫或框架應該假定合理的默認值,而非要求提供不必要的配置。比如說模型中有一個名為 User 的類,那么數據庫中對應的表就會默認命名為 User。只有在偏離這一個約定的時候,例如想要將該表命名為 person,才需要寫有關這個名字的配置。
比如平時架構師搭建項目就是限制軟件開發隨便寫代碼,制定出一套規范,讓開發人員按統一的要求進行開發編碼測試之類的,這樣就加強了開發效率與審查代碼效率。所以說寫代碼的時候就需要按要求命名,這樣統一規范的代碼就有良好的可讀性與維護性了。
約定優于配置簡單來理解,就是遵循約定。
Spring Boot 是所有基于 Spring 開發的項目的起點。Spring Boot 的設計是為了盡可能快的跑起來 Spring 應用程序并且盡可能減少配置文件。
SpringBoot 概念
Spring 優缺點分析
優點:Spring 是 Java 企業版(Java Enterprise Edition,JEE,也稱 J2EE)的輕量級代替品。無需開發重量級的 Enterprise Java Bean - EJB,Spring 為企業級 Java 開發提供了一種相對簡單的方法,通過依賴注入和面向切面編程,用簡單的 Java 對象(Plain Old Java Object,POJO)實現了 EJB 的功能。
缺點:雖然 Spring 的組件代碼是輕量級的,但它的配置卻是重量級的。一開始,Spring 用 XML 配置,而且是很多 XML 配 置。Spring 2.5 引入了基于注解的組件掃描,這消除了大量針對應用程序自身組件的顯式 XML 配置。Spring 3.0 引入 了基于 Java 的配置,這是一種類型安全的可重構配置方式,可以代替 XML。
所有這些配置都代表了開發時的損耗。因為在思考 Spring 特性配置和解決業務問題之間需要進行思維切換,所以編寫配置擠占了編寫應用程序邏輯的時間。和所有框架一樣,Spring 實用,但與此同時它要求的回報也不少。
除此之外,項目的依賴管理也是一件耗時耗力的事情。在環境搭建時,需要分析要導入哪些庫的坐標,而且還需要分析導入與之有依賴關系的其他庫的坐標,一旦選錯了依賴的版本,隨之而來的不兼容問題就會嚴重阻礙項目的開發進度。SSM 整合:Spring、Spring MVC、Mybatis、Spring-Mybatis 整合包、數據庫驅動,引入依賴的數量繁多、容易存在版本沖突。
Spring Boot 解決上述 Spring 的問題
SpringBoot 對上述 Spring 的缺點進行的改善和優化,基于約定優于配置的思想,可以讓開發人員不必在配置與邏輯業務之間進行思維的切換,全身心的投入到邏輯業務的代碼編寫中,從而大大提高了開發的效率,一定程度上縮短了項目周期。
起步依賴:
起步依賴本質上是一個?Maven?項目對象模型?(Project?Object?Model,POM),定義了對其他庫的傳遞依賴,這些東西加在一起即支持某項功能。?簡單的說,起步依賴就是將具備某種功能的依賴坐標打包到一起,并提供一些默認的功能。
自動配置:
springboot?的自動配置,指的是?springboot?會自動將一些配置類的?bean?注冊進?ioc?容器,在需要的地方使用?@autowired?或者?@resource?等注解來使用它。“自動”的表現形式就是只需要引想用功能的包,相關的配置完全不用管,springboot?會自動注入這些配置?bean,直接使用這些?bean?即可。
Springboot 可以簡單、快速、方便地搭建項目;對主流開發框架的無配置集成;極大提高了開發、部署效率。
SpringBoot 入門案例
案例需求:請求 Controller 中的方法,并將返回值響應到頁面。
1) 依賴管理
pom.xml
<parent>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-parentartifactId>
????<version>2.2.2.RELEASEversion>
parent>
<dependencies>
????
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-webartifactId>
????dependency>
dependencies>
<build>
????<plugins>
????????<plugin>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-maven-pluginartifactId>
????????plugin>
????plugins>
build>
2) 啟動類
com.renda.SpringBootDemo1Application
/**?*?SpringBoot?的啟動類通常放在二級包中,
?*?比如:com.renda.SpringBootDemo1Application。
?*?因為?SpringBoot?項目在做包掃描,
?*?會掃描啟動類所在的包及其子包下的所有內容。
?*
?*?@author?Renda?Zhang
?*?@since?2020-10-28?23:11
?*/
@SpringBootApplication?//?標識當前類為?SpringBoot?項目的啟動類
public?class?SpringBootDemo1Application?{
????public?static?void?main(String[]?args)?{
????????//?樣板代碼
????????SpringApplication.run(SpringBootDemo1Application.class,?args);
????}
}
3) Controller
com.renda.controller.HelloController
@RestController@RequestMapping("/hello")
public?class?HelloController?{
????@RequestMapping("/boot")
????public?String?helloSpringBoot()?{
????????return?"Hello?Spring?Boot";
????}
}
SpringBoot 快速構建
案例需求:請求 Controller 中的方法,并將返回值響應到頁面。
1)使用 Spring Initializr 方式構建 Spring Boot 項目
本質上說,Spring Initializr 是一個 Web 應用,它提供了一個基本的項目結構,能夠快速構建一個基礎的 Spring Boot 項目。
注意使用快速方式創建 Spring Boot 項目時,所在主機須在聯網狀態下;本質上是在開發工具執行各項參數后,由 Spring 提供的 URL 所對應的服務器生成, IDEA 將服務器生成的 SpringBoot 項目下載到本地的工作空間中。
Project SDK 用于設置創建項目使用的 JDK 版本,這里,使用之前初始化設置好的 JDK 版本即可;在 Choose Initializr Service URL 下使用默認的初始化服務地址 https://start.spring.io 進行 Spring Boot 項目創建。
創建完成后的 pom 文件
<?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?https://maven.apache.org/xsd/maven-4.0.0.xsd">
????<modelVersion>4.0.0modelVersion>
????<parent>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-parentartifactId>
????????<version>2.2.2.RELEASEversion>
????????<relativePath/>?
????parent>
????<groupId>com.rendagroupId>
????<artifactId>springbootdemo2artifactId>
????<version>0.0.1-SNAPSHOTversion>
????<name>springbootdemo2name>
????<description>Demo?project?for?Spring?Bootdescription>
????<properties>
????????<java.version>11java.version>
????properties>
????<dependencies>
????????<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-webartifactId>
????????dependency>
????????<dependency>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-starter-testartifactId>
????????????<scope>testscope>
????????????<exclusions>
????????????????<exclusion>
????????????????????<groupId>org.junit.vintagegroupId>
????????????????????<artifactId>junit-vintage-engineartifactId>
????????????????exclusion>
????????????exclusions>
????????dependency>
????dependencies>
????<build>
????????<plugins>
????????????<plugin>
????????????????<groupId>org.springframework.bootgroupId>
????????????????<artifactId>spring-boot-maven-pluginartifactId>
????????????plugin>
????????plugins>
????build>
project>
創建完成后,可以刪除自動生成的 .mvn、.gitignore、HELP.md、mvnw、mvnw.cmd。
創建好的 Spring Boot 項目結構如圖:
/src/main/java/????com.renda.Springbootdemo2Application?-?項目主程序啟動類
/src/main/resources/
????static?-?靜態資源文件夾
????templates?-?模板頁面文件夾
????application.properties?-?全網配置文件
/src/test/java/
????com.renda.Springbootdemo2ApplicationTests?-?項目測試類
使用 Spring Initializr 方式構建的 Spring Boot 項目會默認生成項目啟動類、存放前端靜態資源和頁面的文件夾、編寫項目配置的配置文件以及進行項目單元測試的測試類。
2)創建一個用于 Web 訪問的 Controller
注意:確保項目啟動類 Springbootdemo2Application 在 com.renda 包下。
com.renda.controller.HelloController
@RestController@RequestMapping("/hello")
public?class?HelloController?{
????@RequestMapping("/boot")
????public?String?hello()?{
????????return?"What's?up!?Spring?Boot!";
????}
}
3) 運行項目
在 application.properties 中修改 tomcat 的默認端口號:
server.port=8888運行主程序啟動類 Springbootdemo2Application,項目啟動成功后,在控制臺上會發現 Spring Boot 項目默認啟動的端口號為 8888,此時,可以在瀏覽器上訪問 http://localhost:8888/hello/boot。
頁面輸出的內容是 “What's up! Spring Boot!”,至此,構建 Spring Boot 項目就完成了。
單元測試與熱部署
單元測試
開發中,每當完成一個功能接口或業務方法的編寫后,通常都會借助單元測試驗證該功能是否正確。
1)添加 spring-boot-starter-test 測試依賴啟動器,在項目的 pom.xml 文件中添加 spring-boot-starter-test 測試依賴啟動器,示例代碼如下 :
<dependency>????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-testartifactId>
????<scope>testscope>
????<exclusions>
????????<exclusion>
????????????<groupId>org.junit.vintagegroupId>
????????????<artifactId>junit-vintage-engineartifactId>
????????exclusion>
????exclusions>
dependency>
注意:使用 Spring Initializr 方式搭建的 Spring Boot 項目,會自動加入 spring-boot-starter-test 測試依賴啟動器,無需再手動添加。
2)編寫單元測試類和測試方法:
/**?*??SpringJUnit4ClassRunner.class:?Spring?運行環境
?*??JUnit4.class:?JUnit?運行環境
?*??SpringRunner.class:?Spring?Boot?運行環境
?*/
@RunWith(SpringRunner.class)?//?@RunWith:?運行器
@SpringBootTest?//?標記為當前類為?SpringBoot?測試類,加載項目的?ApplicationContext?上下文環境
class?Springbootdemo2ApplicationTests?{
????@Autowired
????private?HelloController?helloController;
????@Test
????void?contextLoads()?{
????????String?result?=?helloController.hello();
????????System.out.println(result);
????}
}
上述代碼中,先使用 @Autowired 注解注入了 HelloController 實例對象,然后在 contextLoads() 方法中調用了 HelloController 類中對應的請求控制方法 hello(),并輸出打印結果。
熱部署
在開發過程中,通常會對一段業務代碼不斷地修改測試,在修改之后往往需要重啟服務,有些服務需要加載很久才能啟動成功,這種不必要的重復操作極大的降低了程序開發效率。為此,Spring Boot 框架專門提供了進行熱部署的依賴啟動器,用于進行項目熱部署,而無需手動重啟項目 。
熱部署:在修改完代碼之后,不需要重新啟動容器,就可以實現更新。
使用步驟:
1)添加 spring-boot-devtools 熱部署依賴啟動器。
在 Spring Boot 項目進行熱部署測試之前,需要先在項目的 pom.xml 文件中添加 spring-boot-devtools 熱部署依賴啟動器:
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-devtoolsartifactId>
dependency>
由于使用的是 IDEA 開發工具,添加熱部署依賴后可能沒有任何效果,接下來還需要針對 IDEA 開發工具進行熱部署相關的功能設置。
2)開啟 IDEA 的自動編譯。
選擇?IDEA?工具界面的?【File】->【Settings】?選項,打開?Compiler?面板設置頁面。選擇?Build?下的?Compiler?選項,在右側勾選?“Build?project?automatically”?選項將項目設置為自動編譯,單擊?【Apply】->【OK】?按鈕保存設置。
3)開啟 IDEA 的在項目運行中自動編譯的功能。
在項目任意頁面中使用組合快捷鍵?“Ctrl+Shift+Alt+/”?打開?Maintenance?選項框,選中并打開?Registry?頁面。列表中找到?“compiler.automake.allow.when.app.running”,將該選項后的?Value?值勾選,用于指定?IDEA?工具在程序運行過程中自動編譯,最后單擊?【Close】?按鈕完成設置。
熱部署效果測試
啟動 Springbootdemo2Application http://localhost:8888/hello/boot
頁面原始輸出的內容是 “What's up! Spring Boot!”。
為了測試配置的熱部署是否有效,接下來,在不關閉當前項目的情況下,將 HelloController 類中的請求處理方法 hello() 的返回值修改為 “Hello! Spring Boot!” 并保存,查看控制臺信息會發現項目能夠自動構建和編譯,說明項目熱部署生效。
再次刷新瀏覽器,輸出了 “Hello! Spring Boot!”,說明項目熱部署配置成功。
全局配置文件
全局配置文件能夠對一些默認配置值進行修改。Spring Boot 使用一個 application.properties 或者 application.yaml 的文件作為全局配置文件,該文件存放在 src/main/resource 目錄或者類路徑的 /config,一般會選擇 resource 目錄。
Spring Boot 配置文件的命名及其格式:
application.properties
application.yaml
application.yml
`application.properties` 配置文件
引入相關依賴:
<dependency>????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
????<groupId>mysqlgroupId>
????<artifactId>mysql-connector-javaartifactId>
????<version>6.0.6version>
dependency>
使用 Spring Initializr 方式構建 Spring Boot 項目時,會在 resource 目錄下自動生成一個空的 application.properties 文件,Spring Boot 項目啟動時會自動加載 application.properties 文件。
#?修改?tomcat?的版本號server.port=8080
#?定義數據庫的連接信息?JdbcTemplate
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/renda01
spring.datasource.username=root
spring.datasource.password=password
可以在 application.properties 文件中定義 Spring Boot 項目的相關屬性,當然,這些相關屬性可以是系統屬性、環境變量、命令參數等信息,也可以是自定義配置文件名稱和位置。
預先準備了兩個實體類文件,后續會演示將 application.properties 配置文件中的自定義配置屬性注入到 Person 實體類的對應屬性中。
1)先在項目的 com.renda 包下創建一個 pojo 包,并在該包下創建兩個實體類 Pet 和 Person。
/**?*?寵物類
?*
?*?@author?Renda?Zhang
?*?@since?2020-10-29?1:03
?*/
public?class?Pet?{
????//?品種
????private?String?type;
????//?名稱
????private?String?name;
????//?setter?and?getter,?toString?...
}
/**
?*?人類
?*
?*?@author?Renda?Zhang
?*?@since?2020-10-29?1:04
?*/
@Component
/**
?*?將配置文件中所有以?person?開頭的配置信息注入當前類中
?*?前提?1:必須保證配置文件中?person.xx?與當前?Person?類的屬性名一致
?*?前提?2:必須保證當前?Person?中的屬性都具有?set?方法
?*/
@ConfigurationProperties(prefix?=?"person")
public?class?Person?{
????//?id
????private?int?id;
????//?名稱
????private?String?name;
????//?愛好
????private?List?hobby;
????//?家庭成員
????private?String[]?family;
????private?Map?map;
????//?寵物
????private?Pet?pet;
????//?setter?and?getter,?toString?...
}
@ConfigurationProperties(prefix = "person") 注解的作用是將配置文件中以 person 開頭的屬性值通過 setXX() 方法注入到實體類對應屬性中。
@Component 注解的作用是將當前注入屬性值的 Person 類對象作為 Bean 組件放到 Spring 容器中,只有這樣才能被 @ConfigurationProperties 注解進行賦值。
2)打開項目的 resources 目錄下的 application.properties 配置文件,在該配置文件中編寫需要對 Person 類設置的配置屬性。
#?自定義配置信息注入到?Person?對象中person.id=100
person.name=張人大
##?list
person.hobby=看書,寫代碼,吃飯
##?String[]
person.family=兄弟,父母
##?map
person.map.k1=v1
person.map.k2=v2
##?pet?對象
person.pet.type=dog
person.pet.name=旺財
3)查看 application.properties 配置文件是否正確,同時查看屬性配置效果,打開通過 IDEA 工具創建的項目測試類,在該測試類中引入 Person 實體類 Bean,并進行輸出測試。
@RunWith(SpringRunner.class)@SpringBootTest
class?Springbootdemo2ApplicationTests?{
????@Autowired
????private?Person?person;
????@Test
????void?showPersonInfo()?{
????????System.out.println(person);
????}
}
可以看出,測試方法 showPersonInfo() 運行成功,同時正確打印出了 Person 實體類對象。至此,說明 application.properties 配置文件屬性配置正確,并通過相關注解自動完成了屬性注入。
4)解決瀏覽器請求出現中文亂碼問題。
調整文件編碼格式:Settings -> Editor -> File Encodings -> 確保 Global Encoding 和 Project Encoding 為 UTF-8,修改 Default ecoding for properties files 為 UTF-8 并勾選 Transparent native-to-ascii conversion。
application.properties 文件中增加配置:
#?解決中文亂碼server.tomcat.uri-encoding=UTF-8
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
`application.yaml` 配置文件
YAML 文件格式是 Spring Boot 支持的一種 JSON 文件格式,相較于傳統的 Properties 配置文件,YAML 文件以數據為核心,是一種更為直觀且容易被電腦識別的數據序列化格式。application.yaml 配置文件的工作原理和 application.properties 是一樣的,只不過 yaml 格式配置文件看起來更簡潔一些。
YAML 文件的擴展名可以使用 .yml 或者 .yaml。
application.yml 文件使用 key: value 格式配置屬性,使用縮進控制層級關系。
SpringBoot 的三種配置文件是可以共存的:application.properties、application.yaml、application.yml。
1)value 值為普通數據類型(例如數字、字符串、布爾等)
當 YAML 配置文件中配置的屬性值為普通數據類型時,可以直接配置對應的屬性值,同時對于字符串類型的屬性值,不需要額外添加引號,示例代碼如下:
server:??port:?8080
??servlet:
????context-path:?/hello
2)value 值為數組和單列集合
當 YAML 配置文件中配置的屬性值為數組或單列集合類型時,主要有兩種書寫方式:縮進式寫法和行內式寫法。
其中,縮進式寫法還有兩種表示形式,示例代碼如下:
person:???hobby:?
????-?play
????-?read
????-?sleep?
或者使用如下示例形式:
person:??hobby:
????play,
????read,
????sleep
上述代碼中,在 YAML 配置文件中通過兩種縮進式寫法對 person 對象的單列集合(或數組)類型的愛好 hobby 賦值為 play、read 和 sleep。其中一種形式為 “- 屬性值”,另一種形式為多個屬性值之前加英文逗號分隔;注意,最后一個屬性值后不要加逗號。
person:???hobby:?[play,read,sleep]
通過上述示例對比發現,YAML 配置文件的行內式寫法更加簡明、方便。另外,包含屬性值的中括號 “[]” 還可以進一步省略,在進行屬性賦值時,程序會自動匹配和校對。
3)value 值為 Map 集合和對象
當 YAML 配置文件中配置的屬性值為 Map 集合或對象類型時,YAML 配置文件格式同樣可以分為兩種書寫方式 - 縮進式寫法和行內式寫法。
其中,縮進式寫法的示例代碼如下:
person:???map:?
????k1:?v1
????k2:?v2
對應的行內式寫法示例代碼如下:
person:??map:?{k1:?v1,k2:?v2}
在YAML配置文件中,配置的屬性值為Map集合或對象類型時,縮進式寫法的形式按照YAML文件格式編寫即可,而行內式寫法的屬性值要用大括號“{}”包含。
接下來,在 Properties 配置文件演示案例基礎上,注釋掉 Properties 中跟 Person 相關的注入,然后通過配置 application.yaml 配置文件對 Person 對象進行賦值,具體使用如下。
在項目的 resources 目錄下,新建一個 application.yaml 配置文件,在該配置文件中編寫為 Person 類設置的配置屬性:
person:??id:?1000
??name:?張人大
??hobby:
????-?跑步
????-?瑜伽
????-?游泳
??family:
????-?張小明
????-?李小紅
??map:
????k1:?這是?k1?對應的?value
????k2:?這是?k2?對應的?value
??pet:
????type:?dog
????name:?金毛
再次執行測試。
可以看出,測試方法 showPersonInfo() 同樣運行成功,并正確打印出了 Person 實體類對象。
需要說明的是,本次使用 application.yaml 配置文件進行測試時需要提前將 application.properties 配置文件中編寫的配置注釋,這是因為 application.properties 配置文件會覆蓋 application.yaml 配置文件。
配置文件屬性值的注入
從 spring-boot-starter-parent 的 pom 文件可以知道配置文件的優先級從低到高如下:
<includes>????<include>**/application*.ymlinclude>
????<include>**/application*.yamlinclude>
????<include>**/application*.propertiesinclude>
includes>
使用 Spring Boot 全局配置文件設置屬性時:
如果配置屬性是?Spring?Boot?已有屬性,例如服務端口?server.port,那么?Spring?Boot?內部會自動掃描并讀取這些配置文件中的屬性值并覆蓋默認屬性。如果配置的屬性是用戶自定義屬性,例如剛剛自定義的?Person?實體類屬性,還必須在程序中注入這些配置屬性方可生效。
Spring Boot 支持多種注入配置文件屬性的方式,下面來介紹如何使用注解 @ConfigurationProperties 和 @Value 注入屬性。
使用 `@ConfigurationProperties` 注入屬性
Spring Boot 提供的 @ConfigurationProperties 注解用來快速、方便地將配置文件中的自定義屬性值批量注入到某個 Bean 對象的多個對應屬性中。假設現在有一個配置文件,如果使用 @ConfigurationProperties 注入配置文件的屬性,示例代碼如下:
@Component@ConfigurationProperties(prefix?=?"person")
public?class?Person?{
????private?int?id;
????private?String?name;
????private?List?hobby;
????private?String[]?family;
????private?Map?map;
????private?Pet?pet;
????//?setter?and?getter,?toString?...
}
上述代碼使用 @Component 和 @ConfigurationProperties(prefix = “person”) 將配置文件中的每個屬性映射到 person 類組件中。
使用 `@Value` 注入屬性
@Value 注解是 Spring 框架提供的,用來讀取配置文件中的屬性值并逐個注入到 Bean 對象的對應屬性中,Spring Boot 框架從 Spring 框架中對 @Value 注解進行了默認繼承,所以在 Spring Boot 框架中還可以使用該注解讀取和注入配置文件屬性值。使用 @Value 注入屬性的示例代碼如下:
@Componentpublic?class?Student?{
????@Value("${person.id}")
????private?int?number;
????//?getter?setter?toString?...
}
上述代碼中,使用 @Component 和 @Value 注入 Person 實體類的id屬性。其中,@Value 不僅可以將配置文件的屬性注入 Person 的 id 屬性,還可以直接給 id 屬性賦值,這點是@ConfigurationProperties 不支持的。
1)在 com.renda.pojo 包下新創建一個實體類 Student,并使用 @Value 注解注入屬性:
@Componentpublic?class?Student?{
????@Value("${person.id}")
????private?String?number;
????@Value("${person.name}")
????private?String?name;
????//?getter?setter?toString?...
}
Student 類使用 @Value 注解將配置文件的屬性值讀取和注入。
從上述示例代碼可以看出,使用 @Value 注解方式需要對每一個屬性注入設置,同時又免去了屬性的 setXX() 方法。
2)再次打開測試類進行測試:
@RunWith(SpringRunner.class)@SpringBootTest
class?Springbootdemo2ApplicationTests?{
????@Autowired
????private?Student?student;
????@Test
????public?void?showStudentInfo(){
????????System.out.println(student);
????}
}
可以看出,測試方法 showStudentInfo() 運行成功,同時正確打印出了 Student 實體類對象。需要說明的是,本示例中只是使用 @Value 注解對實例中 Student 對象的普通類型屬性進行了賦值演示,而 @Value 注解對于包含 Map 集合、對象以及 YAML 文件格式的行內式寫法的配置文件的屬性注入都不支持,如果賦值會出現錯誤。
自定義配置
Spring Boot 免除了項目中大部分的手動配置,對于一些特定情況,可以通過修改全局配置文件以適應具體生產環境,可以說,幾乎所有的配置都可以寫在 application.yml 文件中,Spring Boot 會自動加載全局配置文件從而免除手動加載的煩惱。但是,如果自定義配置文件,Spring Boot 是無法識別這些配置文件的,此時就需要手動加載。
使用 `@PropertySource` 加載配置文件
對于這種加載自定義配置文件的需求,可以使用 @PropertySource 注解來實現。@PropertySource 注解用于指定自定義配置文件的具體位置和名稱。
如果需要將自定義配置文件中的屬性值注入到對應類的屬性中,可以使用 @ConfigurationProperties 或者 @Value 注解進行屬性值注入。
1)打開 Spring Boot 項目的 resources 目錄,在項目的類路徑下新建一個 my.properties 自定義配置文件,在該配置文件中編寫需要設置的配置屬性。
#?對實體類對象?Product?進行屬性配置product.id=99
product.name=小米
2)在 com.renda.pojo 包下新創建一個配置類 Product,提供 my.properties 自定義配置文件中對應的屬性,并根據 @PropertySource 注解的使用進行相關配置。
@Component@PropertySource("classpath:my.properties")
@ConfigurationProperties(prefix?=?"product")
public?class?Product?{
????private?int?id;
????private?String?name;
????//?getter?setter?toString?...
}
主要是一個自定義配置類,通過相關注解引入了自定義的配置文件,并完成了自定義屬性值的注入。針對示例中的幾個注解,具體說明如下:
@PropertySource("classpath:my.properties") 注解指定了自定義配置文件的位置和名稱,此示例表示自定義配置文件為 classpath 類路徑下的 my.properties 文件。
@ConfigurationProperties(prefix = "product") 注解將上述自定義配置文件 my.properties 中以 product 開頭的屬性值注入到該配置類屬性中。
3)進行測試。
@RunWith(SpringRunner.class)@SpringBootTest
class?Springbootdemo2ApplicationTests?{
????@Autowired
????private?Product?product;
????@Test
????public?void?showProductInfo()?{
????????System.out.println(product);
????}
}
使用 `@Configuration` 編寫自定義配置類
在 Spring Boot 框架中,推薦使用配置類的方式向容器中添加和配置組件。
在 Spring Boot 框架中,通常使用 @Configuration 注解定義一個配置類,Spring Boot 會自動掃描和識別配置類,從而替換傳統 Spring 框架中的 XML 配置文件。
當定義一個配置類后,還需要在類中的方法上使用 @Bean 注解進行組件配置,將方法的返回對象注入到 Spring 容器中,并且組件名稱默認使用的是方法名,當然也可以使用 @Bean 注解的 name 或 value 屬性自定義組件的名稱。
1)在項目下新建一個 com.renda.config 包,并在該包下新創建一個類 MyService,該類中不需要編寫任何代碼:
package?com.renda.service;public?class?MyService?{
}
創建了一個空的 MyService 類,而該類目前沒有添加任何配置和注解,因此還無法正常被 Spring Boot 掃描和識別。
2)在項目的 com.renda.config 包下,新建一個類 MyConfig,并使用 @Configuration 注解將該類聲明一個配置類,內容如下:
@Configuration?//?標識當前類是一個配置類,SpringBoot?會掃描該類,將所有標識?@Bean?注解的方法的返回值注入的容器中public?class?MyConfig?{
????@Bean?//?注入的名稱就是方法的名稱,注入的類型就是返回值的類型
????public?MyService?myService(){
????????return?new?MyService();
????}
????@Bean("service_")
????public?MyService?myService2(){
????????return?new?MyService();
????}
}
MyConfig 是 @Configuration 注解聲明的配置類(類似于聲明了一個 XML 配置文件),該配置類會被 Spring Boot 自動掃描識別;使用 @Bean 注解的 myService() 方法,其返回值對象會作為組件添加到了 Spring 容器中(類似于 XML 配置文件中的標簽配置),并且該組件的 id 默認是方法名 myService。
3)測試類:
@RunWith(SpringRunner.class)@SpringBootTest
class?Springbootdemo2ApplicationTests?{
????@Autowired
????private?ApplicationContext?applicationContext;
????@Test
????public?void?testConfig(){
????????System.out.println(applicationContext.containsBean("myService"));
????????System.out.println(applicationContext.containsBean("service_"));
????}
}
上述代碼中,先通過 @Autowired 注解引入了 Spring 容器實例 ApplicationContext,然后在測試方法 testConfig() 中測試查看該容器中是否包括 id 為 myService 和 service_ 的組件。
從測試結果可以看出,測試方法 testConfig() 運行成功,顯示運行結果為 true,表示 Spirng 的 IOC 容器中也已經包含了 id 為 myService 和 service_的實例對象組件,說明使用自定義配置類的形式完成了向 Spring 容器進行組件的添加和配置。
SpringBoot 原理深入及源碼剖析
依賴管理
在 Spring Boot 入門程序中,項目 pom.xml 文件有兩個核心依賴,分別是 spring-boot-starter-
parent 和 spring-boot-starter-web,關于這兩個依賴的相關介紹具體如下:
spring-boot-starter-parent 依賴
<parent>????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-parentartifactId>
????<version>2.2.2.RELEASEversion>
????<relativePath/>
parent>
上述代碼中,將 spring-boot-starter-parent 依賴作為 Spring Boot 項目的統一父項目依賴管理,并將項目版本號統一為 2.2.2.RELEASE,該版本號根據實際開發需求是可以修改的。
使用 “Ctrl+鼠標左鍵” 進入并查看 spring-boot-starter-parent 底層源文件,發現 spring-boot-
starter-parent 的底層有一個父依賴 spring-boot-dependencies,核心代碼具體如下
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-dependenciesartifactId>
????<version>2.2.2.RELEASEversion>
????<relativePath>../../spring-boot-dependenciesrelativePath>
parent>
繼續查看 spring-boot-dependencies 底層源文件,核心代碼具體如下:
<properties>????<activemq.version>5.15.11activemq.version>
????...
????<solr.version>8.2.0solr.version>
????<spring-amqp.version>2.2.2.RELEASEspring-amqp.version>
????<spring-batch.version>4.2.1.RELEASEspring-batch.version>
????<spring-cloud-connectors.version>2.0.7.RELEASEspring-cloud-connectors.version>
????<spring-data-releasetrain.version>Moore-SR3spring-data-releasetrain.version>
????<spring-framework.version>5.2.2.RELEASEspring-framework.version>
????<spring-hateoas.version>1.0.2.RELEASEspring-hateoas.version>
????<spring-integration.version>5.2.2.RELEASEspring-integration.version>
????<spring-kafka.version>2.3.4.RELEASEspring-kafka.version>
????<spring-ldap.version>2.3.2.RELEASEspring-ldap.version>
????<spring-restdocs.version>2.0.4.RELEASEspring-restdocs.version>
????<spring-retry.version>1.2.4.RELEASEspring-retry.version>
????<spring-security.version>5.2.1.RELEASEspring-security.version>
????<spring-session-bom.version>Corn-RELEASEspring-session-bom.version>
????<spring-ws.version>3.0.8.RELEASEspring-ws.version>
????<sqlite-jdbc.version>3.28.0sqlite-jdbc.version>
????<sun-mail.version>${jakarta-mail.version}sun-mail.version>
????<thymeleaf.version>3.0.11.RELEASEthymeleaf.version>
????<thymeleaf-extras-data-attribute.version>2.0.1thymeleaf-extras-data-attribute.version>
????...
properties>
從 spring-boot-dependencies 底層源文件可以看出,該文件通過標簽對一些常用技術框架的依賴文件進行了統一版本號管理,例如 activemq、spring、tomcat 等,都有與 Spring Boot 2.2.2 版本相匹配的版本,這也是 pom.xml 引入依賴文件不需要標注依賴文件版本號的原因。
需要說明的是,如果 pom.xml 引入的依賴文件不是 spring-boot-starter-parent 管理的,那么在 pom.xml 引入依賴文件時,需要使用標簽指定依賴文件的版本號。
spring-boot-starter-web 依賴
spring-boot-starter-parent 父依賴啟動器的主要作用是進行版本統一管理;項目運行依賴的 JAR 包是從 Spring Boot Starters 中導入。
查看 spring-boot-starter-web 依賴文件源碼,核心代碼具體如下:
<dependencies>????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starterartifactId>
????????<version>2.2.2.RELEASEversion>
????????<scope>compilescope>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-jsonartifactId>
????????<version>2.2.2.RELEASEversion>
????????<scope>compilescope>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-tomcatartifactId>
????????<version>2.2.2.RELEASEversion>
????????<scope>compilescope>
????dependency>
????<dependency>
????????<groupId>org.springframework.bootgroupId>
????????<artifactId>spring-boot-starter-validationartifactId>
????????<version>2.2.2.RELEASEversion>
????????<scope>compilescope>
????????<exclusions>
????????????<exclusion>
????????????????<artifactId>tomcat-embed-elartifactId>
????????????????<groupId>org.apache.tomcat.embedgroupId>
????????????exclusion>
????????exclusions>
????dependency>
????<dependency>
????????<groupId>org.springframeworkgroupId>
????????<artifactId>spring-webartifactId>
????????<version>5.2.2.RELEASEversion>
????????<scope>compilescope>
????dependency>
????<dependency>
????????<groupId>org.springframeworkgroupId>
????????<artifactId>spring-webmvcartifactId>
????????<version>5.2.2.RELEASEversion>
????????<scope>compilescope>
????dependency>
dependencies>
從上述代碼可以發現,spring-boot-starter-web 依賴啟動器的主要作用是提供 Web 開發場景所需的底層所有依賴。
正是如此,在 pom.xml 中引入 spring-boot-starter-web 依賴啟動器時,就可以實現 Web 場景開發,而不需要額外導入 Tomcat 服務器以及其他 Web 依賴文件等。當然,這些引入的依賴文件的版本號還是由 spring-boot-starter-parent 父依賴進行的統一管理。
Spring Boot Starters:
https://github.com/spring-projects/spring-boot/tree/v2.1.0.RELEASE/spring-boot-project/spring-boot-starters
https://mvnrepository.com/search?q=starter
Spring Boot 除了提供有上述介紹的 Web 依賴啟動器外,還提供了其他許多開發場景的相關依賴,可以打開 Spring Boot 官方文檔,搜索 “Starters” 關鍵字查詢場景依賴啟動器。
需要說明的是,Spring Boot 官方并不是針對所有場景開發的技術框架都提供了場景啟動器,例如數據庫操作框架 MyBatis、阿里巴巴的 Druid 數據源等,Spring Boot 官方就沒有提供對應的依賴啟動器。為了充分利用 Spring Boot 框架的優勢,在 Spring Boot 官方沒有整合這些技術框架的情況下,MyBatis、Druid 等技術框架所在的開發團隊主動與 Spring Boot 框架進行了整合,實現了各自的依賴啟動器,例如 mybatis-spring-boot-starter、druid-spring-boot-starter 等。在 pom.xml 文件中引入這些第三方的依賴啟動器時,切記要配置對應的版本號。
自動配置
概念:能夠在添加 jar 包依賴的時候,自動配置一些組件的相關配置,無需手動配置或者只需要少量手動配置就能運行編寫的項目。
Spring Boot 應用的啟動入口是 @SpringBootApplication 注解標注類中的 main() 方法。
@SpringBootApplication:SpringBoot 應用標注在某個類上說明這個類是 SpringBoot 的主配置類, SpringBoot 就應該運行這個類的 main() 方法啟動 SpringBoot 應用。
進入到 @SpringBootApplication 內:
//?注解的適用范圍,?Type?表示注解可以描述在類、接口、注解或枚舉中@Target(ElementType.TYPE)
//?表示注解的生命周期,Runtime?運行時
@Retention(RetentionPolicy.RUNTIME)
//?表示注解可以記錄在?javadoc?中
@Documented
//?表示可以被子類繼承該注解
@Inherited
//?標明該類為?Spring?Boot?配置類
@SpringBootConfiguration
//?啟動自動配置功能
@EnableAutoConfiguration
@ComponentScan(excludeFilters?=?{?@Filter(type?=?FilterType.CUSTOM,?classes?=?TypeExcludeFilter.class),
????????@Filter(type?=?FilterType.CUSTOM,?classes?=?AutoConfigurationExcludeFilter.class)?})
public?@interface?SpringBootApplication?{
????//?根據?class?來排除特定的類,使其不能加入?spring?容器,傳入參數?value?類型是?class?類型。
????@AliasFor(annotation?=?EnableAutoConfiguration.class)
????Class>[]?exclude()?default?{};
????//?根據?classname?來排除特定的類,使其不能加入?spring?容器,傳入參數?value?類型是class的全類名字符串數組。
????@AliasFor(annotation?=?EnableAutoConfiguration.class)
????String[]?excludeName()?default?{};
????//?指定掃描包,參數是包名的字符串數組。
????@AliasFor(annotation?=?ComponentScan.class,?attribute?=?"basePackages")
????String[]?scanBasePackages()?default?{};
????//?掃描特定的包,參數類似是?Class?類型數組。
????@AliasFor(annotation?=?ComponentScan.class,?attribute?=?"basePackageClasses")
????Class>[]?scanBasePackageClasses()?default?{};
????...???
}
從上述源碼可以看出,@SpringBootApplication 注解是一個組合注解,前面 4 個是注解的元數據信息, 主要看后面 3 個注解:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 三個核心注解。
@SpringBootConfiguration 注解
@SpringBootConfiguration: SpringBoot 的配置類,標注在某個類上,表示這是一個 ?SpringBoot 的配置類。
查看 @SpringBootConfiguration 注解源碼:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public?@interface?SpringBootConfiguration?{
????...
}
從上述源碼可以看出,@SpringBootConfiguration 注解內部有一個核心注解 @Configuration,該注解是 Spring 框架提供的,表示當前類為一個配置類(XML 配置文件的注解表現形式),并可以被組件掃描器掃描。由此可見,@SpringBootConfiguration 注解的作用與 @Configuration 注解相同,都是標識一個可以被組件掃描器掃描的配置類,只不過 @SpringBootConfiguration 是被 Spring Boot 進行了重新封裝命名而已。
`@EnableAutoConfiguration` 注解
@EnableAutoConfiguration:開啟自動配置功能,以前需要手動配置的東西,現在由 ?SpringBoot 自動配置,這個注解就是 Springboot 能實現自動配置的關鍵。
查看該注解內部查看源碼信息,核心代碼具體如下:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//?自動配置包
@AutoConfigurationPackage
//?Spring?的底層注解?@Import,給容器中導入一個組件;導入的組件是AutoConfigurationPackages.Registrar.class
@Import(AutoConfigurationImportSelector.class)
//?告訴?SpringBoot?開啟自動配置功能,這樣自動配置才能生效。
public?@interface?EnableAutoConfiguration?{
????String?ENABLED_OVERRIDE_PROPERTY?=?"spring.boot.enableautoconfiguration";
????//?返回不會被導入到?Spring?容器中的類
????Class>[]?exclude()?default?{};
????//?返回不會被導入到?Spring?容器中的類名
????String[]?excludeName()?default?{};
}
可以發現它是一個組合注解, ?Spring ?中有很多以 Enable 開頭的注解,其作用就是借助 @Import 來收集并注冊特定場景相關的 Bean ,并加載到 IOC 容器。@EnableAutoConfiguration 就是借助 @Import 來收集所有符合自動配置條件的 bean 定義,并加載到 IoC 容器。
@AutoConfigurationPackage 注解
查看 @AutoConfigurationPackage 注解內部源碼信息,核心代碼具體如下:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public?@interface?AutoConfigurationPackage?{
}
從上述源碼可以看出,@AutoConfigurationPackage 注解的功能是由 @Import 注解實現的,它是 spring 框架的底層注解,它的作用就是給容器中導入某個組件類,例如 @Import(AutoConfigurationPackages.Registrar.class),它就是將 Registrar 這個組件類導入到容器中,可查看 Registrar 類中 registerBeanDefinitions 方法,這個方法就是導入組件類的具體實現:
static?class?Registrar?implements?ImportBeanDefinitionRegistrar,?DeterminableImports?{????@Override
????public?void?registerBeanDefinitions(AnnotationMetadata?metadata,?BeanDefinitionRegistry?registry)?{
????????register(registry,?new?PackageImport(metadata).getPackageName());
????}
????@Override
????public?Set?determineImports(AnnotationMetadata?metadata)?{
????????return?Collections.singleton(new?PackageImport(metadata));
????}
}
從上述源碼可以看出,在 Registrar 類中有一個 registerBeanDefinitions() 方法,使用 Debug 模式啟動項目, 可以看到選中的部分就是 com.renda。也就是說,@AutoConfigurationPackage 注解的主要作用就是將主程序類所在包及所有子包下的組件到掃描到 spring 容器中。
因此在定義項目包結構時,要求定義的包結構非常規范,項目主程序啟動類要定義在最外層的根目錄位置,然后在根目錄位置內部建立子包和類進行業務開發,這樣才能夠保證定義的類能夠被組件掃描器掃描。
@Import({AutoConfigurationImportSelector.class}) 注解
將 AutoConfigurationImportSelector 這個類導入到 Spring 容器中,AutoConfigurationImportSelector 可以幫助 Springboot 應用將所有符合條件的 @Configuration 配置都加載到當前 SpringBoot 創建并使用的 IOC 容器 ApplicationContext 中。
繼續研究 AutoConfigurationImportSelector 這個類,通過源碼分析這個類中是通過selectImports 這個方法告訴 springboot 都需要導入那些組件:
@Overridepublic?String[]?selectImports(AnnotationMetadata?annotationMetadata)?{
????if?(!isEnabled(annotationMetadata))?{
????????return?NO_IMPORTS;
????}
????//?獲得自動配置元信息,需要傳入?beanClassLoader?這個類加載器
????AutoConfigurationMetadata?autoConfigurationMetadata?=?AutoConfigurationMetadataLoader
????????.loadMetadata(this.beanClassLoader);
????AutoConfigurationEntry?autoConfigurationEntry?=?getAutoConfigurationEntry(autoConfigurationMetadata,
??????????????????????????????????????????????????????????????????????????????annotationMetadata);
????return?StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
深入研究 loadMetadata 方法 :
//?文件中為需要加載的配置類的類路徑protected?static?final?String?PATH?=?"META-INF/spring-autoconfigure-metadata.properties";
private?AutoConfigurationMetadataLoader()?{
}
static?AutoConfigurationMetadata?loadMetadata(ClassLoader?classLoader)?{
????return?loadMetadata(classLoader,?PATH);
}
static?AutoConfigurationMetadata?loadMetadata(ClassLoader?classLoader,?String?path)?{
????try?{
????????//?讀取?spring-boot-autoconfigure-2.1.5.RELEASE.jar?包中的?spring-autoconfigure-metadata.properties?的信息生成?url
????????Enumeration?urls?=?(classLoader?!=?null)???classLoader.getResources(path)
????????????:?ClassLoader.getSystemResources(path);
????????Properties?properties?=?new?Properties();//?解析?urls?枚舉對象中的信息封裝成?properties?對象并加載while?(urls.hasMoreElements())?{
????????????properties.putAll(PropertiesLoaderUtils.loadProperties(new?UrlResource(urls.nextElement())));
????????}//?根據封裝好的?properties?對象生成?AutoConfigurationMetadata?對象并返回return?loadMetadata(properties);
????}catch?(IOException?ex)?{throw?new?IllegalArgumentException("Unable?to?load?@ConditionalOnClass?location?["?+?path?+?"]",?ex);
????}
}
AutoConfigurationImportSelector 類 getAutoConfigurationEntry 方法:
protected?AutoConfigurationEntry?getAutoConfigurationEntry(AutoConfigurationMetadata?autoConfigurationMetadata,?AnnotationMetadata?annotationMetadata)?{????//?判斷?EnabledAutoConfiguration?注解有沒有開啟,?默認開啟
????if?(!isEnabled(annotationMetadata))?{
????????return?EMPTY_ENTRY;
????}
????//?獲得注解的屬性信息
????AnnotationAttributes?attributes?=?getAttributes(annotationMetadata);
????//?獲取默認支持的自動配置類列表
????List?configurations?=?getCandidateConfigurations(annotationMetadata,?attributes);//?去重
????configurations?=?removeDuplicates(configurations);//?去除一些多余的配置類,根據?@EnabledAutoConfiguration?的?exclusions?屬性進行排除
????Set?exclusions?=?getExclusions(annotationMetadata,?attributes);
????checkExcludedClasses(configurations,?exclusions);
????configurations.removeAll(exclusions);//?根據?pom?文件中加入的依賴文件篩選中最終符合當前項目運行環境對應的自動配置類
????configurations?=?filter(configurations,?autoConfigurationMetadata);//?觸發自動配置導入監聽事件
????fireAutoConfigurationImportEvents(configurations,?exclusions);return?new?AutoConfigurationEntry(configurations,?exclusions);
}
深入 getCandidateConfigurations 方法:
這個方法中有一個重要方法 loadFactoryNames,這個方法是讓 SpringFactoryLoader 去加載一些組件的名字。
protected?List?getCandidateConfigurations(AnnotationMetadata?metadata,?AnnotationAttributes?attributes)?{????/**
?????*?loadFactoryNames:
?????*?這個方法需要傳入兩個參數?getSpringFactoriesLoaderFactoryClass()?和?
?????*?getBeanClassLoader()。
?????*?getSpringFactoriesLoaderFactoryClass()?這個方法返回的是
?????*?@EnableAutoConfiguration.class。
?????*?getBeanClassLoader()?這個方法返回的是?beanClassLoader?類加載器
?????*/
????List?configurations?=?SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),?getBeanClassLoader());
????Assert.notEmpty(configurations,?"No?auto?configuration?classes?found?in?META-INF/spring.factories.?If?you?"?+?"are?using?a?custom?packaging,?make?sure?that?file?is?correct.");return?configurations;
}/**
?*?Return?the?class?used?by?{@link?SpringFactoriesLoader}?to?load?configuration
?*?candidates.
?*?@return?the?factory?class
?*/protected?Class>?getSpringFactoriesLoaderFactoryClass()?{return?EnableAutoConfiguration.class;
}
...@Overridepublic?void?setBeanClassLoader(ClassLoader?classLoader)?{this.beanClassLoader?=?classLoader;
}protected?ClassLoader?getBeanClassLoader()?{return?this.beanClassLoader;
}
繼續點開 loadFactoryNames 方法:
public?static?List?loadFactoryNames(Class>?factoryType,?@Nullable?ClassLoader?classLoader)?{????//?獲取出入的鍵
????String?factoryTypeName?=?factoryType.getName();
????return?loadSpringFactories(classLoader).getOrDefault(factoryTypeName,?Collections.emptyList());
}
private?static?Map>?loadSpringFactories(@Nullable?ClassLoader?classLoader)?{
????MultiValueMap?result?=?cache.get(classLoader);if?(result?!=?null)?{return?result;
????}try?{//?如果類加載器不為?null,則加載類路徑下?spring.factories?文件,將其中設置的配置類的全路徑信息封裝為?Enumeration?類對象
????????Enumeration?urls?=?(classLoader?!=?null???classLoader.getResources(FACTORIES_RESOURCE_LOCATION)?:?ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
????????result?=?new?LinkedMultiValueMap<>();//?循環?Enumeration?類對象,根據相應的節點信息生成?Properties?對象,通過傳入的鍵獲取值,在將值切割為一個個小的字符串轉化為?Array,加入方法?result?集合中while?(urls.hasMoreElements())?{
????????????URL?url?=?urls.nextElement();
????????????UrlResource?resource?=?new?UrlResource(url);
????????????Properties?properties?=?PropertiesLoaderUtils.loadProperties(resource);for?(Map.Entry,??>?entry?:?properties.entrySet())?{
????????????????String?factoryTypeName?=?((String)?entry.getKey()).trim();for?(String?factoryImplementationName?:?StringUtils.commaDelimitedListToStringArray((String)?entry.getValue()))?{
????????????????????result.add(factoryTypeName,?factoryImplementationName.trim());
????????????????}
????????????}
????????}
????????cache.put(classLoader,?result);return?result;
????}catch?(IOException?ex)?{throw?new?IllegalArgumentException("Unable?to?load?factories?from?location?["?+?FACTORIES_RESOURCE_LOCATION?+?"]",?ex);
????}
}
上面代碼需要讀取的 FACTORIES_RESOURCE_LOCATION 最終路徑的長這樣,而這個是 spring 提供的一個工具類:
public?static?final?String?FACTORIES_RESOURCE_LOCATION?=?"META-INF/spring.factories";它其實是去加載一個外部的文件,而這文件是在 spring-boot-autoconfigure-2.2.2.RELEASE.jar 包下的 META-INF/spring.factories,打開 spring.factories 文件:
#?Auto?Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
...
@EnableAutoConfiguration 就是從 classpath 中搜尋 META-INF/spring.factories 配置文件,并將其中 org.springframework.boot.autoconfigure.EnableutoConfiguration 對應的配置項通過反射 Java Refletion 實例化為對應的標注了 @Configuration 的 JavaConfig 形式的配置類,并加載到 IOC 容器中。
以入門項目為例,在項目中加入了 Web 環境依賴啟動器,對應的 WebMvcAutoConfiguration 自動配置類就會生效,打開該自動配置類會發現,在該配置類中通過全注解配置類的方式對 Spring MVC 運行所需環境進行了默認配置,包括默認前綴、默認后綴、視圖解析器、MVC 校驗器等。而這些自動配置類的本質是傳統 Spring MVC 框架中對應的 XML 配置文件,只不過在 Spring Boot 中以自動配置類的形式進行了預先配置。因此,在 Spring Boot 項目中加入相關依賴啟動器后,基本上不需要任何配置就可以運行程序,當然,也可以對這些自動配置類中默認的配置進行更改。
總結:
因此?springboot?底層實現自動配置的步驟是:1.?springboot?應用啟動。
2.?@SpringBootApplication?起作用。
3.?@EnableAutoConfiguration。
4.?@AutoConfigurationPackage:這個組合注解主要是?@Import(AutoConfigurationPackages.Registrar.class),它通過將?Registrar?類導入到容器中,而?
Registrar?類作用是掃描主配置類同級目錄以及子包,并將相應的組件導入到?springboot?創建管理的容器中。
5.?@Import(AutoConfigurationImportSelector.class):它通過將AutoConfigurationImportSelector?類導入到容器中;AutoConfigurationImportSelector?類作用是通過?selectImports?方法執行的過程中,會使用內部工具類?SpringFactoriesLoader,查找?classpath?上所有?jar?包中的?META-INF/spring.factories?進行加載,實現將配置類信息交給?SpringFactory?加載器進行一系列的容器創建過程。
@ComponentScan 注解
@ComponentScan 注解具體掃描的包的根路徑由 Spring Boot 項目主程序啟動類所在包位置決定,在掃描過程中由前面介紹的 @AutoConfigurationPackage 注解進行解析,從而得到 Spring Boot 項目主程序啟動類所在包的具體位置。
總結
@SpringBootApplication?的注解的功能簡單來說就是?3?個注解的組合注解:|-?@SpringBootConfiguration
???//?通過?javaConfig?的方式來添加組件到?IOC?容器中
???|-?@Configuration
|-?@EnableAutoConfiguration
???//?自動配置包,與?@ComponentScan?掃描到的添加到?IOC
???|-?@AutoConfigurationPackage
???//?到?META-INF/spring.factories?中定義的?bean?添加到?IOC?容器中
???|-?@Import(AutoConfigurationImportSelector.class)?
//?包掃描
|-?@ComponentScan
SpringBoot 數據訪問
Spring Boot 整合 MyBatis
MyBatis 是一款優秀的持久層框架,Spring Boot 官方雖然沒有對 MyBatis 進行整合,但是 MyBatis 團隊自行適配了對應的啟動器,進一步簡化了使用 MyBatis 進行數據的操作。
因為 Spring Boot 框架開發的便利性,所以實現 Spring Boot 與數據訪問層框架(例如 MyBatis)的整合非常簡單,主要是引入對應的依賴啟動器,并進行數據庫相關參數設置即可。
基礎環境搭建
1)數據準備
在 MySQL 中,先創建了一個數據庫 springbootdata,然后創建了兩個表 t_article 和 t_comment 并向表中插入數據。其中評論表 t_comment 的 a_id 與文章表 t_article 的主鍵 id 相關聯。
#?創建數據庫CREATE?DATABASE?IF?NOT?EXISTS?springbootdata?DEFAULT?CHARACTER?SET?utf8;
#?選擇使用數據庫
USE?springbootdata;
#?創建表?t_article?并插入相關數據
DROP?TABLE?IF?EXISTS?t_article;
CREATE?TABLE?t_article
(
????id??????int(20)?NOT?NULL?AUTO_INCREMENT?COMMENT?'文章id',
????title???varchar(200)?DEFAULT?NULL?COMMENT?'文章標題',
????content?longtext?COMMENT?'文章內容',
????PRIMARY?KEY?(id)
)?ENGINE?=?InnoDB?AUTO_INCREMENT?=?2?DEFAULT?CHARSET=utf8;
INSERT?INTO?t_article?VALUES?(1,?'Spring?Boot?基礎入門',?'從入門到精通講解...');
INSERT?INTO?t_article?VALUES?(2,?'Spring?Cloud?基礎入門',?'從入門到精通講解...');
#?創建表?t_comment?并插入相關數據
DROP?TABLE?IF?EXISTS?t_comment;
CREATE?TABLE?t_comment
(
????id??????int(20)?NOT?NULL?AUTO_INCREMENT?COMMENT?'評論id',
????content?longtext?COMMENT?'評論內容',
????author??varchar(200)?DEFAULT?NULL?COMMENT?'評論作者',
????a_id????int(20)??????DEFAULT?NULL?COMMENT?'關聯的文章id',
????PRIMARY?KEY?(id)
)?ENGINE?=?InnoDB?AUTO_INCREMENT?=?3?DEFAULT?CHARSET=utf8;
INSERT?INTO?t_comment?VALUES?(1,?'很全、很詳細',?'lucy',?1);
INSERT?INTO?t_comment?VALUES?(2,?'贊一個',?'tom',?1);
INSERT?INTO?t_comment?VALUES?(3,?'很詳細',?'eric',?1);
INSERT?INTO?t_comment?VALUES?(4,?'很好,非常詳細',?'張三',?1);
INSERT?INTO?t_comment?VALUES?(5,?'很不錯',?'李四',?2);
2)創建項目,引入相應的啟動器
使用 Spring Initializr 來初始化項目。
項目名:springbootmybatis
包名:com.renda
啟動器:SQL 的 MyBatis Framework、MySQL Driver,Web 的 Spring Web
3)編寫與數據庫表 t_comment 和 t_article 對應的實體類 Comment 和 Article
com.renda.pojo.Comment
public?class?Comment?{????private?Integer?id;
????private?String?content;
????private?String?author;
????private?Integer?aId;
????//?getter?setter?toString?...
}
com.renda.pojo.Article
public?class?Article?{????private?Integer?id;
????private?String?title;
????private?String?content;
????//?getter?setter?toString?...
}
4)編寫配置文件
application.properties ?更名為 application.yml。在 application.properties 配置文件中進行數據庫連接配置:
spring:??datasource:
????url:?jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC&characterEncoding=UTF-8
????username:?root
????password:?password
注解方式整合 Mybatis
需求:實現通過 ID 查詢 Comment 信息。
1)創建一個對 t_comment 表數據操作的接口 CommentMapper
com.renda.mapper.CommentMapper
public?interface?CommentMapper?{????@Select("select?*?from?t_comment?where?id?=?#{id}")
????Comment?findById(Integer?id);
}
2)在 Spring Boot 項目啟動類上添加 @MapperScan("xxx") 注解
com.renda.SpringbootmybatisApplication
@SpringBootApplication@MapperScan("com.renda.bootmybatis.mapper")?//執行掃描mapper的包名
public?class?SpringbootmybatisApplication?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(SpringbootmybatisApplication.class,?args);
????}
}
3)編寫測試方法
導入 Junit 的依賴,增加測試方法:
com.renda.SpringbootmybatisApplicationTests
@RunWith(SpringRunner.class)@SpringBootTest
class?SpringbootmybatisApplicationTests?{
????@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
????@Autowired
????private?CommentMapper?commentMapper;
????@Test
????void?findCommentById()?{
????????Comment?comment?=?commentMapper.findById(1);
????????System.out.println(comment);
????}
}
控制臺中查詢的 Comment 的 aId 屬性值為 null,沒有映射成功。這是因為編寫的實體類 Comment 中使用了駝峰命名方式將 t_comment 表中的 a_id 字段設計成了 aId 屬性,所以無法正確映射查詢結果。
為了解決上述由于駝峰命名方式造成的表字段值無法正確映射到類屬性的情況,可以在 Spring Boot 全局配置文件 application.yml 中添加開啟駝峰命名匹配映射配置,示例代碼如下:
mybatis:??configuration:
????#?開啟駝峰命名匹配映射
????map-underscore-to-camel-case:?true
配置文件的方式整合 MyBatis
第一、二步驟使用 Free Mybatis plugin 插件生成:使用 IDEA 連接 Database,然后選中要自動生成代碼的表,右鍵 -> mybatis-generator -> 按照需求輸入信息,點擊 ok。
1)創建一個用于對數據庫表 t_article 數據操作的接口 ArticleMapper
public?interface?ArticleMapper?{????int?deleteByPrimaryKey(Integer?id);
????int?insert(Article?record);
????int?insertSelective(Article?record);
????Article?selectByPrimaryKey(Integer?id);
????int?updateByPrimaryKeySelective(Article?record);
????int?updateByPrimaryKey(Article?record);
}
2)創建 XML 映射文件
resources 目錄下創建一個統一管理映射文件的包 mapper,并在該包下編寫與 ArticleMapper 接口方應的映射文件 ArticleMapper.xml
<?xml ?version="1.0"?encoding="UTF-8"?>mapper?PUBLIC?"-//mybatis.org//DTD?Mapper?3.0//EN"?"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper?namespace="com.renda.mapper.ArticleMapper">
??<resultMap?id="BaseResultMap"?type="com.renda.pojo.Article">
????<id?column="id"?jdbcType="INTEGER"?property="id"?/>
????<result?column="title"?jdbcType="VARCHAR"?property="title"?/>
????<result?column="content"?jdbcType="VARCHAR"?property="content"?/>
??resultMap>
??<sql?id="Base_Column_List">
????id,?title,?content
??sql>
??<select?id="selectByPrimaryKey"?parameterType="java.lang.Integer"?resultMap="BaseResultMap">
????select?
????<include?refid="Base_Column_List"?/>
????from?t_article
????where?id?=?#{id,jdbcType=INTEGER}
??select>
??<delete?id="deleteByPrimaryKey"?parameterType="java.lang.Integer">
????delete?from?t_article
????where?id?=?#{id,jdbcType=INTEGER}
??delete>
??<insert?id="insert"?keyColumn="id"?keyProperty="id"?parameterType="com.renda.pojo.Article"?useGeneratedKeys="true">
????insert?into?t_article?(title,?content)
????values?(#{title,jdbcType=VARCHAR},?#{content,jdbcType=VARCHAR})
??insert>
??<insert?id="insertSelective"?keyColumn="id"?keyProperty="id"?parameterType="com.renda.pojo.Article"?useGeneratedKeys="true">
????insert?into?t_article
????<trim?prefix="("?suffix=")"?suffixOverrides=",">
??????<if?test="title?!=?null">
????????title,
??????if>
??????<if?test="content?!=?null">
????????content,
??????if>
????trim>
????<trim?prefix="values?("?suffix=")"?suffixOverrides=",">
??????<if?test="title?!=?null">
????????#{title,jdbcType=VARCHAR},
??????if>
??????<if?test="content?!=?null">
????????#{content,jdbcType=VARCHAR},
??????if>
????trim>
??insert>
??<update?id="updateByPrimaryKeySelective"?parameterType="com.renda.pojo.Article">
????update?t_article
????<set>
??????<if?test="title?!=?null">
????????title?=?#{title,jdbcType=VARCHAR},
??????if>
??????<if?test="content?!=?null">
????????content?=?#{content,jdbcType=VARCHAR},
??????if>
????set>
????where?id?=?#{id,jdbcType=INTEGER}
??update>
??<update?id="updateByPrimaryKey"?parameterType="com.renda.pojo.Article">
????update?t_article
????set?title?=?#{title,jdbcType=VARCHAR},
??????content?=?#{content,jdbcType=VARCHAR}
????where?id?=?#{id,jdbcType=INTEGER}
??update>
mapper>
3)配置 XML 映射文件路徑
在項目中編寫的 XML 映射文件,Spring Boot 并無從知曉,所以無法掃描到該自定義編寫的 XML 配置文件,還必須在全局配置文件 application.yml 中添加 MyBatis 映射文件路徑的配置,同時需要添加實體類別名映射路徑,示例代碼如下:
mybatis:??configuration:
????#?開啟駝峰命名匹配映射
????map-underscore-to-camel-case:?true
??#?加載?resources/mapper?文件夾下的所有的?xml?文件
??mapper-locations:?classpath:mapper/*.xml
??#?配置?XML?映射文件中指定的實體類別名路徑
??type-aliases-package:?com.renda.pojo
4)編寫單元測試進行接口方法測試
@RunWith(SpringRunner.class)@SpringBootTest
class?SpringbootmybatisApplicationTests?{
????@Autowired
????private?ArticleMapper?articleMapper;
????@Test
????void?findArticleById()?{
????????Article?article?=?articleMapper.selectByPrimaryKey(1);
????????System.out.println(article);
????}
}
Spring Boot 整合 Redis
1)添加Redis依賴包
在項目的 pom.xml 中添加如下:
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
2)配置 Redis 數據庫連接
在 application.yml 中配置redis數據庫連接信息,如下:
spring:??redis:
????#?Redis?服務器地址
????host:?192.168.186.128
????#?Redis?服務器連接端口
????port:?6379
????jedis:
??????pool:
????????#?連接池最大連接數(使用負值表示沒有限制)
????????max-active:?18
????????#?連接池最大阻塞等待時間(使用負值表示沒有限制)
????????max-wait:?3000
????????#?連接池中的最大空閑連接
????????max-idle:?20
????????#?連接池中的最小空閑連接
????????min-idle:?2
????#?連接超時時間(毫秒)
????timeout:?3000
????#?Redis?數據庫索引(默認為?0)
????database:?0
3)編寫 Redis 操作工具類
將 RedisTemplate 實例包裝成一個工具類,便于對 redis 進行數據操作。
package?com.renda.util;import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.data.redis.core.RedisTemplate;
import?org.springframework.stereotype.Component;
import?java.util.concurrent.TimeUnit;
/**
?*?@author?Renda?Zhang
?*?@since?2020-10-30?1:00
?*/
@Component
public?class?RedisUtils?{
????@Autowired
????private?RedisTemplate?redisTemplate;
????/**
?????*?讀取緩存
?????*/
????public?Object?get(final?String?key)?{
????????return?redisTemplate.opsForValue().get(key);
????}
????/**
?????*?寫入緩存
?????*/
????public?boolean?set(String?key,?Object?value)?{
????????boolean?result?=?false;
????????try?{
????????????redisTemplate.opsForValue().set(key,?value,?1,?TimeUnit.DAYS);
????????????result?=?true;
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????????return?result;
????}
????/**
?????*?更新緩存
?????*/
????public?boolean?getAndSet(final?String?key,?String?value)?{
????????boolean?result?=?false;
????????try?{
????????????redisTemplate.opsForValue().getAndSet(key,?value);
????????????result?=?true;
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????????return?result;
????}
????/**
?????*?刪除緩存
?????*/
????public?boolean?delete(final?String?key)?{
????????boolean?result?=?false;
????????try?{
????????????redisTemplate.delete(key);
????????????result?=?true;
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????????return?result;
????}
}
4)測試
寫一個測試用例類來完成對 redis 的整合。
@RunWith(SpringRunner.class)@SpringBootTest
class?SpringbootmybatisApplicationTests?{
????//?寫入,key:1,value:mysql?數據庫中?id?為?1?的?article?記錄
????@Autowired
????private?RedisUtils?redisUtils;
????@Test
????void?writeRedis()?{
????????redisUtils.set("1",?articleMapper.selectByPrimaryKey(1));
????????System.out.println("success");
????}
????@Test
????void?readRedis()?{
????????Article?article?=?(Article)?redisUtils.get("1");
????????System.out.println(article);
????}
}
SpringBoot 視圖技術
支持的視圖技術
前端模板引擎技術的出現,使前端開發人員無需關注后端業務的具體實現,只關注自己頁面的呈現效果即可,并且解決了前端代碼錯綜復雜的問題、實現了前后端分離開發。Spring Boot 框架對很多常用的模板引擎技術(如:FreeMarker、Thymeleaf、Mustache 等)提供了整合支持。
Spring Boot 不太支持常用的 JSP 模板,并且沒有提供對應的整合配置,這是因為使用嵌入式 Servlet 容器的 Spring Boot 應用程序對于 JSP 模板存在一些限制 :
在 Jetty 和 Tomcat 容器中,Spring Boot 應用被打包成 war 文件可以支持 JSP。但 Spring Boot 默認使用嵌入式 Servlet 容器以 JAR 包方式進行項目打包部署,這種 JAR 包方式不支持 JSP。
如果使用 Undertow 嵌入式容器部署 Spring Boot 項目,也不支持 JSP 模板。(Undertow ?是紅帽公司開發的一款基于 NIO 的高性能 Web 嵌入式服務器)
Spring Boot 默認提供了一個處理請求路徑 “/error” 的統一錯誤處理器,返回具體的異常信息。使用 JSP 模板時,無法對默認的錯誤處理器進行覆蓋,只能根據 Spring Boot 要求在指定位置定制錯誤頁面。
Thymeleaf
Thymeleaf 是一種現代的基于服務器端的 Java 模板引擎技術,也是一個優秀的面向 Java 的 XML、XHTML、HTML5 頁面模板,它具有豐富的標簽語言、函數和表達式,在使用 Spring Boot 框架進行頁面設計時,一般會選擇 Thymeleaf 模板。
Thymeleaf 語法
在 HTML 頁面上使用 Thymeleaf 標簽,Thymeleaf 標簽能夠動態地替換掉靜態內容,使頁面動態展示。
為了更直觀的認識 Thymeleaf,下面展示一個在 HTML 文件中嵌入了 Thymeleaf 的頁面文件,示例代碼如下:
html><html?lang="en"?xmlns:th="http://www.thymeleaf.org">
????<head>
????????<meta?charset="UTF-8">
????????<link?rel="stylesheet"?type="text/css"?media="all"href="../../css/gtvg.css"?th:href="@{/css/gtvg.css}"?/>
????????<title>Thymeleaftitle>
????head>
????<body>
????????<p?th:text="${hello}">Hello?Thymeleafp>
????body>
html>
上述代碼中,“xmlns:th="http://www.thymeleaf.org" 用于引入 Thymeleaf 模板引擎標簽,使用關鍵字 th 標注標簽是 Thymeleaf 模板提供的標簽,其中,th:href="@{/css/gtvg.css}" 用于引入外聯樣式文件,th:text="${hello}" 用于動態顯示標簽文本內容。
常用標簽:
th:insert - 布局標簽,替換內容到引入的文件
th:replace - 頁面片段包含(類似 JSP 中的 include 標簽)
th:each - 元素遍歷(類似 JSP 中的 c:forEach 標簽)
th:if - 條件判斷,如果為真
th:unless - 條件判斷,如果為假
th:switch - 條件判斷,進行選擇性匹配
th:case - 條件判斷,進行選擇性匹配
th:value - 屬性值修改,指定標簽屬性值
th:href - 用于設定鏈接地址
th:src - 用于設定鏈接地址
th:text - 用于指定標簽顯示的文本內容
標準表達式:
變量表達式- ?${…}
選擇變量表達式 - *{…}
消息表達式 - #{…}
鏈接 URL 表達式 - @{…}
片段表達式 - ~{…}
變量表達式 `${…}`
變量表達式 ${...} 主要用于獲取上下文中的變量值,示例代碼如下:
<p?th:text="${title}">這是標題p>示例使用了 Thymeleaf 模板的變量表達式 ${...} 用來動態獲取 P 標簽中的內容,如果當前程序沒有啟動或者當前上下文中不存在 title 變量,該片段會顯示標簽默認值“這是標題”;如果當前上下文中存在 title 變量并且程序已經啟動,當前 P 標簽中的默認文本內容將會被 title 變量的值所替換,從而達到模板引擎頁面數據動態替換的效果。
同時,Thymeleaf 為變量所在域提供了一些內置對象,具體如下所示:
#ctx:上下文對象#vars:上下文變量
#locale:上下文區域設置
#request:(僅限?Web?Context)HttpServletRequest?對象
#response:(僅限?Web?Context)HttpServletResponse?對象
#session:(僅限?Web?Context)HttpSession?對象
#servletContext:(僅限?Web?Context)ServletContext?對象
結合上述內置對象的說明,假設要在 Thymeleaf 模板引擎頁面中動態獲取當前國家信息,可以使用 #locale 內置對象,示例代碼如下:
The?locale?country?is:?<span?th:text="${#locale.country}">Chinaspan>上述代碼中,使用 th:text="${#locale.country}" 動態獲取當前用戶所在國家信息,其中標簽內默認內容為 China,程序啟動后通過瀏覽器查看當前頁面時,Thymeleaf 會通過瀏覽器語言設置來識別當前用戶所在國家信息,從而實現動態替換。
選擇變量表達式 `*{…}`
選擇變量表達式和變量表達式用法類似,一般用于從被選定對象而不是上下文中獲取屬性值,如果沒有選定對象,則和變量表達式一樣,示例代碼如下:
<div?th:object="${book}">????<p>titile:?<span?th:text="*{title}">標題span>.p>
div>
*{title} 選擇變量表達式獲取當前指定對象 book 的 title 屬性值。
消息表達式 `#{…}`
消息表達式 #{...} 主要用于 Thymeleaf 模板頁面國際化內容的動態替換和展示,使用消息表達式 #{...} 進行國際化設置時,還需要提供一些國際化配置文件。
鏈接表達式 `@{…}`
鏈接表達式 @{...} 一般用于頁面跳轉或者資源的引入,在 Web 開發中占據著非常重要的地位,并且使用也非常頻繁,示例代碼如下:
<a?th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">viewa>?<a?th:href="@{/order/details(orderId=${o.id},pid=${p.id})}">viewa>
上述代碼中,鏈接表達式 @{...} 分別編寫了絕對鏈接地址和相對鏈接地址。在有參表達式中,需要按照 @{路徑(參數名稱=參數值,參數名稱=參數值...)} 的形式編寫,同時該參數的值可以使用變量表達式來傳遞動態參數值。
片段表達式 `~{…}`
片段表達式 ~{...} 用來標記一個片段模板,并根據需要移動或傳遞給其他模板。其中,最常見的用法是使用 th:insert 或 th:replace 屬性插入片段,示例代碼如下:
<div?th:insert="~{thymeleafDemo::title}">div>上述代碼中,使用 th:insert 屬性將 title 片段模板引用到該標簽中。thymeleafDemo 為模板名稱,Thymeleaf 會自動查找 /resources/templates/ 目錄下的 thymeleafDemo 模板,title 為片段名稱。
基本使用
1) Thymeleaf 模板基本配置
首先在 Springbootdemo2 項目中使用 Thymeleaf 模板,首先必須保證引入 Thymeleaf 依賴,示例代碼如下:
<dependency>????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
其次,在全局配置文件中配置 Thymeleaf 模板的一些參數。一般 Web 項目都會使用下列配置,示例代碼如:
spring:??thymeleaf:
????#?在開發階段,為了驗證建議關閉緩存
????cache:?true
????#?模板編碼
????encoding:?UTF-8
????#?應用于模板的模板模式
????mode:?HTML5
????#?指定模板頁面存放路徑
????prefix:?classpath:/templates/
????#?指定模板頁面名稱的后綴
????suffix:?.html
上述配置中,spring.thymeleaf.cache 表示是否開啟 Thymeleaf 模板緩存,默認為 true,在開發過程中通常會關閉緩存,保證項目調試過程中數據能夠及時響應;spring.thymeleaf.prefix 指定了 Thymeleaf 模板頁面的存放路徑,默認為classpath:/templates/;spring.thymeleaf.suffix 指定了 Thymeleaf 模板頁面的名稱后綴,默認為 .html。
2)靜態資源的訪問
開發 Web 應用時,難免需要使用靜態資源。Spring boot 默認設置了靜態資源的訪問路徑。
使用 Spring Initializr 方式創建的 Spring Boot 項目,默認生成了一個 resources 目錄,在 resources 目錄中的 public、resources、static 三個子目錄下,Spring boot 默認會挨個從public、resources、static 里面查找靜態資源。
完成數據的頁面展示
1)創建 Spring Boot 項目,引入 Thymeleaf 依賴。
2)編寫配置文件。
編輯 application.yml 全局配置文件,在該文件中對 Thymeleaf 模板頁面的數據緩存進行設置。
#?thymeleaf?頁面緩存設置(默認為?true),開發中方便調試應設置為?false,上線穩定后應保持默認?truespring:
??thymeleaf:
????cache:?false
使用 spring.thymeleaf.cache=false 將 Thymeleaf 默認開啟的緩存設置為了 false,用來關閉模板頁面緩存。
3)創建 web 控制類
在項目中創建名為 com.renda.controller 的包,并在該包下創建一個用于前端模板頁面動態數據替換效果測試的訪問實體類 LoginController。
@Controllerpublic?class?LoginController?{
????@RequestMapping("/toLogin")
????public?String?toLoginView(Model?model){
????????model.addAttribute("currentYear",?Calendar.getInstance().get(Calendar.YEAR));
????????return?"login";?//?resources/templates/login.html
????}
}
toLoginView() 方法用于向登錄頁面 login.html 跳轉,同時攜帶了當前年份信息 currentYear。
4)創建模板頁面并引入靜態資源文件。
在 classpath:/templates/ 目錄下引入一個用戶登錄的模板頁面 login.html。
html><html?lang="en"?xmlns:th="http://www.thymeleaf.org">
<head>
????<meta?http-equiv="Content-Type"?content="text/html;?charset=UTF-8">
????<meta?name="viewport"?content="width=device-width,?initial-scale=1,shrink-to-fit=no">
????<title>用戶登錄界面title>
????<link?th:href="@{../static/css/bootstrap.min.css}"?rel="stylesheet">
????<link?th:href="@{../static/css/signin.css}"?rel="stylesheet">
head>
<body?class="text-center">
<form?class="form-signin">
????<img?class="mb-4"?th:src="@{../static/img/login.png}"?width="72"?height="72">
????<h1?class="h3?mb-3?font-weight-normal">請登錄h1>
????<input?type="text"?class="form-control"th:placeholder="用戶名"?required=""?autofocus="">
????<input?type="password"?class="form-control"th:placeholder="密碼"?required="">
????<div?class="checkbox?mb-3">
????????<label>
????????????<input?type="checkbox"?value="remember-me">?記住我
????????label>
????div>
????<button?class="btn?btn-lg?btn-primary?btn-block"?type="submit"?>登錄button>
????<p?class="mt-5?mb-3?text-muted">??<span?th:text="${currentYear}">2019span>-<span?th:text="${currentYear}+1">2020span>p>
form>
body>
html>
通過 xmlns:th="http://www.thymeleaf.org 引入了 Thymeleaf 模板標簽;
使用 th:href 和 th:src 分別引入了兩個外聯的樣式文件和一個圖片;
使用 th:text 引入了后臺動態傳遞過來的當前年份 currentYear。
5)效果測試
可以看出,登錄頁面 login.html 顯示正常,在頁面底部動態顯示了當前日期 2020-2021,而不是文件中的靜態數字 2019-2020。這進一步說明了 Spring Boot 與 Thymeleaf 整合成功,完成了靜態資源的引入和動態數據的顯示。
SpringBoot 實戰演練
實戰技能補充:lombok
<dependency>????<groupId>org.projectlombokgroupId>
????<artifactId>lombokartifactId>
????<version>1.18.12version>
????
????<scope>providedscope>
dependency>
需求:實現用戶的 CRUD 功能
初始化數據庫信息:
DROP?TABLE?IF?EXISTS?`user`;CREATE?TABLE?`user`
(
????id?int(11)?NOT?NULL?AUTO_INCREMENT?COMMENT?'用戶id',
????username?varchar(100)?DEFAULT?NULL?COMMENT?'用戶名',
????password?varchar(100)?DEFAULT?NULL?COMMENT?'密碼',
????birthday?varchar(100)?DEFAULT?NULL?COMMENT?'生日',
????PRIMARY?KEY?(id)
)?ENGINE?=?InnoDB?AUTO_INCREMENT?=?1?DEFAULT?CHARSET=utf8;
INSERT?INTO?`user`?VALUES?(1,?'zhangsan',?'123',?'2020-10-1');
INSERT?INTO?`user`?VALUES?(2,?'lisi',?'123',?'2020-10-2');
INSERT?INTO?`user`?VALUES?(3,?'wangwu',?'123',?'2020-10-10');
INSERT?INTO?`user`?VALUES?(4,?'yuanjing',?'123',?'2020-10-11');
1)創建 springboot 工程
使用 Spring Initializr 新建一個工程 springbootuser,選擇依賴:Developer Tools -> Lombok,Web -> Spring Web,SQL -> [MyBatis Framework、MySQL Driver]。
2)編輯 pom.xml
<dependency>
????<groupId>com.alibabagroupId>
????<artifactId>druidartifactId>
????<version>1.1.3version>
dependency>
3)User 實體類編寫
使用 FreeMyBatis 生成實體類。
使用 FreeMyBatis 生成 UserMapper 相關的代碼。
com.renda.pojo.User
@Data?//?Lombok?自動生成?getter?和?setterpublic?class?User?implements?Serializable?{
????/**
?????*?用戶id
?????*/
????private?Integer?id;
????/**
?????*?用戶名
?????*/
????private?String?username;
????/**
?????*?密碼
?????*/
????private?String?password;
????/**
?????*?生日
?????*/
????private?String?birthday;
????private?static?final?long?serialVersionUID?=?1L;
}
4)UserMapper 編寫及 xml 文件
com.renda.mapper.UserMapper
public?interface?UserMapper?{????int?deleteByPrimaryKey(Integer?id);
????int?insert(User?record);
????int?insertSelective(User?record);
????User?selectByPrimaryKey(Integer?id);
????int?updateByPrimaryKeySelective(User?record);
????int?updateByPrimaryKey(User?record);
}
src\main\resources\mapper\UserMapper.xml
<?xml ?version="1.0"?encoding="UTF-8"?>mapper?PUBLIC?"-//mybatis.org//DTD?Mapper?3.0//EN"?"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper?namespace="com.renda.mapper.UserMapper">
??<resultMap?id="BaseResultMap"?type="com.renda.pojo.User">
????<id?column="id"?jdbcType="INTEGER"?property="id"?/>
????<result?column="username"?jdbcType="VARCHAR"?property="username"?/>
????<result?column="password"?jdbcType="VARCHAR"?property="password"?/>
????<result?column="birthday"?jdbcType="VARCHAR"?property="birthday"?/>
??resultMap>
??<sql?id="Base_Column_List">
????id,?username,?`password`,?birthday
??sql>
??<select?id="selectByPrimaryKey"?parameterType="java.lang.Integer"?resultMap="BaseResultMap">
????select?
????<include?refid="Base_Column_List"?/>
????from?user
????where?id?=?#{id,jdbcType=INTEGER}
??select>
??<delete?id="deleteByPrimaryKey"?parameterType="java.lang.Integer">
????delete?from?user
????where?id?=?#{id,jdbcType=INTEGER}
??delete>
??<insert?id="insert"?keyColumn="id"?keyProperty="id"?parameterType="com.renda.pojo.User"?useGeneratedKeys="true">
????insert?into?user?(username,?`password`,?birthday
??????)
????values?(#{username,jdbcType=VARCHAR},?#{password,jdbcType=VARCHAR},?#{birthday,jdbcType=VARCHAR}
??????)
??insert>
??<insert?id="insertSelective"?keyColumn="id"?keyProperty="id"?parameterType="com.renda.pojo.User"?useGeneratedKeys="true">
????insert?into?user
????<trim?prefix="("?suffix=")"?suffixOverrides=",">
??????<if?test="username?!=?null">
????????username,
??????if>
??????<if?test="password?!=?null">
????????`password`,
??????if>
??????<if?test="birthday?!=?null">
????????birthday,
??????if>
????trim>
????<trim?prefix="values?("?suffix=")"?suffixOverrides=",">
??????<if?test="username?!=?null">
????????#{username,jdbcType=VARCHAR},
??????if>
??????<if?test="password?!=?null">
????????#{password,jdbcType=VARCHAR},
??????if>
??????<if?test="birthday?!=?null">
????????#{birthday,jdbcType=VARCHAR},
??????if>
????trim>
??insert>
??<update?id="updateByPrimaryKeySelective"?parameterType="com.renda.pojo.User">
????update?user
????<set>
??????<if?test="username?!=?null">
????????username?=?#{username,jdbcType=VARCHAR},
??????if>
??????<if?test="password?!=?null">
????????`password`?=?#{password,jdbcType=VARCHAR},
??????if>
??????<if?test="birthday?!=?null">
????????birthday?=?#{birthday,jdbcType=VARCHAR},
??????if>
????set>
????where?id?=?#{id,jdbcType=INTEGER}
??update>
??<update?id="updateByPrimaryKey"?parameterType="com.renda.pojo.User">
????update?user
????set?username?=?#{username,jdbcType=VARCHAR},
??????`password`?=?#{password,jdbcType=VARCHAR},
??????birthday?=?#{birthday,jdbcType=VARCHAR}
????where?id?=?#{id,jdbcType=INTEGER}
??update>
mapper>
5)UserService 接口及實現類編寫
com.renda.service.UserService
public?interface?UserService?{????/**
?????*?查詢所有
?????*/
????List?queryAll();
????/**
?????*?通過?ID?查詢
?????*/
????User?findById(Integer?id);
????/**
?????*?新增
?????*/
????void?insert(User?user);
????/**
?????*?通過?ID?刪除
?????*/
????void?deleteById(Integer?id);
????/**
?????*?修改
?????*/
????void?update(User?user);
}
com.renda.service.impl.UserServiceImpl
@Servicepublic?class?UserServiceImpl?implements?UserService?{
????@Autowired
????private?UserMapper?userMapper;
????@Override
????public?List?queryAll()?{
????????return?userMapper.queryAll();
????}
????@Override
????public?User?findById(Integer?id)?{
????????return?userMapper.selectByPrimaryKey(id);
????}
????@Override
????public?void?insert(User?user)?{
????????//?將除?id?外所有的列都拼接入?SQL?語句
????????//?userMapper.insert(user);
????????//?只將不為空的列才拼接入?SQL?語句(優先使用,減少高并發下數據傳輸)
????????userMapper.insertSelective(user);
????}
????@Override
????public?void?deleteById(Integer?id)?{
????????userMapper.deleteByPrimaryKey(id);
????}
????@Override
????public?void?update(User?user)?{
????????userMapper.updateByPrimaryKeySelective(user);
????}
}
6)UserController 編寫
com.renda.controller.UserController
/**?*?restful?格式進行訪問
?*?查詢:GET
?*?新增:?POST
?*?更新:PUT
?*?刪除:?DELETE
?*
?*?@author?Renda?Zhang
?*?@since?2020-10-31?1:36
?*/
@RestController
@RequestMapping("/user")
public?class?UserController?{
????@Autowired
????private?UserService?userService;
????/**
?????*?查詢所有
?????*/
????@GetMapping("/query")
????public?List?queryAll(){
????????return?userService.queryAll();
????}
????/**
?????*?通過?ID?查詢
?????*/
????@GetMapping("/query/{id}")
????public?User?queryById(@PathVariable?Integer?id){
????????return?userService.findById(id);
????}
????/**
?????*?刪除
?????*/
????@DeleteMapping("/delete/{id}")
????public?String?delete(@PathVariable?Integer?id){
????????userService.deleteById(id);
????????return?"刪除成功";
????}
????/**
?????*?新增
?????*/
????@PostMapping("/insert")
????public?String?insert(User?user){
????????userService.insert(user);
????????return?"新增成功";
????}
????/**
?????*?修改
?????*/
????@PutMapping("/update")
????public?String?update(User?user){
????????userService.update(user);
????????return?"修改成功";
????}
}
7)全局配置文件 application.yml
重命名 application.properties 為 application.yml
src\main\resources\application.yml
#?服務器配置server:
??port:?8090
spring:
??#?數據源配置
??datasource:
????name:?druid
????type:?com.alibaba.druid.pool.DruidDataSource
????url:?jdbc:mysql://localhost:3306/springbootdata?characterEncoding=utf-8&serverTimezone=UTC
????username:?root
????password:?password
#?整合?MyBatis
mybatis:
??#?聲明?MyBatis?文件所在的位置
??mapper-locations:?classpath:mapper/*Mapper.xml
8)啟動類
com.renda.SpringbootuserApplication
@SpringBootApplication//?使用的?Mybatis,?掃描?com.renda.mapper
@MapperScan("com.renda.mapper")
public?class?SpringbootuserApplication?{
????public?static?void?main(String[]?args)?{
????????SpringApplication.run(SpringbootuserApplication.class,?args);
????}
}
10)使用 Postman 測試
GET http://localhost:8090/user/query
GET http://localhost:8090/user/query/1
POST http://localhost:8090/user/insert?username=renda&password=123456&birthday=1995-12-27
PUT http://localhost:8090/user/update?username=RendaZhang&password=00000&birthday=1997-12-27&id=5
DELETE http://localhost:8090/user/delete/5
Spring Boot 項目部署
需求:將 Spring Boot 項目使用 maven 指令打成 jar 包并運行測試。
分析
1)添加打包組件將項目中的資源、配置、依賴包打到一個 jar 包中;可以使用 maven 的 package 命令。
2)部署:java -jar 包名
步驟實現
確保 pom.xml 文件中有如下的打包組件:
<build>????<plugins>
????????
????????<plugin>
????????????<groupId>org.springframework.bootgroupId>
????????????<artifactId>spring-boot-maven-pluginartifactId>
????????plugin>
????plugins>
build>
部署運行:
java?-jar?springbootuser-0.0.1-SNAPSHOT.jar總結
以上是生活随笔為你收集整理的springboot pom文件指定jdk_Spring Boot 入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么往integer型数组添加数据_面试
- 下一篇: python 美化输出_python基础