天天看點

深入淺出Spring Boot架構--6個知識點小結!一、SpringBoot簡介二、第一個SpringBoot程式三、快速建立SpringBoot項目四、配置檔案五、SpringBoot自動配置原理六、Web開發

一、SpringBoot簡介

1.什麼是SpringBoot

産生背景:Spring開發比較繁瑣,配置檔案很多,部署流程複雜,整合第三方架構難度大。這會降低開發效率

SpringBoot是一個簡化Spring應用建立和開發的架構

整合了整個Spring技術棧,是JavaEE開發一站式解決方案

2.為什麼使用SpringBoot

優點:

  • 可以快速構架Spring項目,并與主流架構進行內建
  • 内置Servlet容器,不需要手動部署war包
  • 使用starter管理依賴并進行版本控制
  • 大量自動配置,簡化開發
  • 提供準生産環境的運作時監控
  • 不需要XML檔案

二、第一個SpringBoot程式

1.操作步驟

步驟:

1.1 建立一個Maven的jar工程

傳統的應用需要建立web工程,然後将應用打成war包,然後部署在容器中

而SpringBoot隻需要打成一個jar包,其中内置了tomcat

1.2 導入SpringBoot相關依賴

<?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>com.ly</groupId> <artifactId>springboot01-helloworld</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> </parent> <name>springboot01-helloworld</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> </build></project>           

複制

1.3 建立Controller

package com.ly.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/** * Author: LuYi * Date: 2019/10/27 11:05 * Description: 描述 */@Controllerpublic class HelloController { @RequestMapping("/hello") @ResponseBody public String hello(){ return "Hello World"; }}           

複制

1.4 建立啟動類

package com.ly;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * Author: LuYi * Date: 2019/10/27 11:05 * Description: 使用@SpringBootApplication将類标注成SpringBoot應用 */@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}           

複制

預設會掃描@SpringBootApplication注解所在的包及其子包,也可使用@ComponentScan("com.ly.controller")注解進行指定

1.5 打包

<!--該插件可以将應用打包成一個可執行的jar包--><build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>           

複制

添加該插件,将應用打成可執行的jar包, 執行:java -jar jar檔案

2. 分析HelloWorld

2.1 POM檔案

  • 父工程
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version></parent>           

複制

  • 父工程的父工程:用來管理SpringBoot應用中依賴的版本,進行版本控制
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.9.RELEASE</version> <relativePath>../../spring-boot-dependencies</relativePath></parent>           

複制

  • 依賴:通過starter指定依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>           

複制

  • SpringBoot提供了很多starter(啟動器),分别對應了不同的應用場景,當在項目中引入這些starter時,相應場景的依賴就會被導入進來

2.2 啟動類

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})           

複制

  • @SpringBootApplication
  • 标注在類上,表示這個類是SpringBoot的啟動類,通過該類的Main方法啟動SpringBoot應用
  • @SpringBootConfiguration
  • 标注在類上,表示這個類是SpringBoot的配置類
  • 層級關系:SpringBootConfiguration——>@Configuration——>@Component

@Configuration:标注在類上,表示這個類是Spring的配置類,相當于XML配置檔案

  • @EnableAutoConfiguration
  • 開啟自動配置功能,簡化了以前繁瑣的配置
  • SpringBoot在啟動時會在/META-INF/spring.factories中EnableAutoConfiguration指定的值,将這些值作為自動配置類添加到容器中,這些自動配置類會幫我們完成很多配置工作。
  • @ComponentScan
  • 标注在類上,指定要掃描的包及其子包

三、快速建立SpringBoot項目

1.簡介

使用Spring initializer快速建構SpringBoot項目

2. 基本操作

  • pom檔案和主程式類自動生成,直接寫業務邏輯即可
  • resources檔案夾的目錄結構
|-static	存放靜态資源,如js,css,images|-template	存放模闆引擎,如freemarker、thymeleaf等|-application.properties	SpringBoot應用的配置檔案,可以修改預設設定           

複制

四、配置檔案

1.簡介

SpringBoot的預設全局配置檔案有兩種:

  • application.properties
  • application.yml

檔案名固定,存放在classpath:/或classpath:/config/目錄下

深入淺出Spring Boot架構--6個知識點小結!一、SpringBoot簡介二、第一個SpringBoot程式三、快速建立SpringBoot項目四、配置檔案五、SpringBoot自動配置原理六、Web開發

可以修改Spring Boot預設配置,具體參考: http://docs.spring.io/spring-boot…

注意:SpringBoot2.0和1.0的配置有差別,有的配置項已被删除

2.YAML用法

2.1 簡介

YAML不是一種标記語言,YAML是專門用來寫配置檔案的,它以資料為中心,簡介強大,比xml和properties更适合做配置檔案

YAML檔案以.yml或.yaml為後置名

2.2 application.yml

server: port: 8081	#寫法:key: value 冒号後面必須有空格 servlet: context-path: /springboot03/           

複制

2.3 文法規則

  • 大小寫敏感
  • 使用縮進表示層級關系
  • 縮進時不允許使用Tab鍵
  • 縮進的空格數目不重要,但是要與對應的層級的左側對齊
  • #表示注釋

2.4 基本用法

YAML支援的資料結構有三種:

  • 字面量:單個的,不可再分的值(字元串、數字、boolean值)
  • 對象:鍵值對集合
  • 數組:一組按次序排列的值

三種資料結構的用法:

1.字面量:普通的值,如數字、字元串、布爾值

number: 12.5str: helloname: 'tom cruise' #如字元串包含空格及特殊字元需要使用 引号 引起來name: 'tom \n cruise' #不會對特殊字元進行轉義 結果為:tom 換行 cruisename: "tom \n cruise" #對特殊字元進行轉義,會作為普通字元輸出, 結果為 tom \n cruise           

複制

  1. 對象,也成為映射Map,包含屬性和值
# 寫法1:換行寫user: name: tom age: 20 sex: male # 寫法2:行内寫法user: {name: tom, age: 20, sex: male}           

複制

  1. 數組,如List、Set等
# 寫法1: 一組短橫線開頭的行names:  - tom - jack - alice # 寫法2: 行内寫法name: {tom,jack,alice}           

複制

3. 為屬性注入值

通過加載配置檔案,為類中的屬性注入值

3.1 編寫application.yml

user: username: admin age: 21 status: true birthday: 2019/2/14 address: province: 黑龍江省 city: 哈爾濱市 lists: - list1 - list2 - list3 maps: {k1: v1,k2: v2}           

複制

3.2 建立實體類

User

package com.luyi.bean;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import java.util.Date;import java.util.List;import java.util.Map;/** * Author: LuYi * Date: 2019/10/27 13:49 * Description: 通過加載配置檔案為目前類中的屬性注入值 */// 必須将目前類加入到容器@Component// 預設讀取全局配置檔案擷取值,目前類中的所有屬性與 user 進行綁定@ConfigurationProperties(value = "user")public class User { private String username; private Integer age; private Boolean status; private Date birthday; private Address address; private List<String> lists; private Map<String, Object> maps; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public List<String> getLists() { return lists; } public void setLists(List<String> lists) { this.lists = lists; } public Map<String, Object> getMaps() { return maps; } public void setMaps(Map<String, Object> maps) { this.maps = maps; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", age=" + age + ", status=" + status + ", birthday=" + birthday + ", address=" + address + ", lists=" + lists + ", maps=" + maps + '}'; }}           

複制

Address

package com.luyi.bean;/** * Author: LuYi * Date: 2019/10/27 13:50 * Description: 描述 */public class Address { private String province; private String city; public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Address{" + "province='" + province + '\'' + ", city='" + city + '\'' + '}'; }}           

複制

3.3 測試

package com.luyi.springboot03config;import com.luyi.bean.User;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass Springboot03ConfigApplicationTests { @Autowired private User user; @Test void contextLoads() { System.out.println(user); }}           

複制

3.4 添加配置檔案處理器依賴(可選)

<!--配置檔案處理器,自動生成中繼資料資訊,編寫配置檔案會有提示--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional></dependency>           

複制

3.5 使用properties配置檔案

user.username=aliceuser.age=22user.status=falseuser.birthday=2019/10/27user.address.province=黑龍江省user.address.city=哈爾濱user.lists=list1,list2,list3user.maps.k1=v1user.maps.k2=v2           

複制

注意:在IDEA中預設使用UTF-8編碼,properties檔案預設使用ASCII編碼,是以會出現亂碼,可通過勾選解決

深入淺出Spring Boot架構--6個知識點小結!一、SpringBoot簡介二、第一個SpringBoot程式三、快速建立SpringBoot項目四、配置檔案五、SpringBoot自動配置原理六、Web開發

優先級:properties > yml

3.6 使用@Value注解注入值

@Value("${user.username}")private String username;@Value("${user.age}")private Integer age;@Value("${user.status}")private Boolean status;@Value("${user.birthday}")private Date birthday;//@Value不支援複雜類型封裝private Address address;@Value("${user.lists}")private List<String> lists;private Map<String, Object> maps;           

複制

@Value與@ConfigurationProperties比較:

  • 前者隻可以單值注入,後者可以批量注入
  • 前者不支援為複雜類型封裝,後者支援

4.多環境配置

可以為不同環境提供不同配置資訊,如開發環境、測試環境、生産環境等

兩種方式:

  • 建立多個properties檔案
  • 定義yml文檔塊

4.1 建立多個properties檔案

步驟:

1.建立不同環境的properties檔案

檔案命名必須符合aplication-xxx.properties的格式

application-dev.properties

server.port=9991           

複制

application-test.properties

server.port=9992           

複制

application-prod.properties

server.port=9993           

複制

2.在application.properties中指定需要激活的配置

#指定要激活的配置spring.profiles.active=prod           

複制

4.2 定義yml文檔塊

1.在yml中使用三個短橫線定義多個文檔塊

spring: profiles: devserver: port: 9991---spring: profiles: testserver: port: 9992---spring: profiles: prodserver: port: 9993           

複制

2.在第一個文檔塊指定要激活的環境

spring: profiles: active: test---           

複制

5.加載外部配置檔案

5.1 加載properties屬性檔案

問題:@ConfigurationProperties預設是從全局配置檔案中讀取值,如果想自定義屬性檔案中擷取值怎麼辦?

解決:使用@PropertySource注解加載外部屬性檔案

// 必須将目前類加入到容器@Component//加載外部的屬性檔案@PropertySource({"classpath:user.properties"})// 預設讀取全局配置檔案擷取值,目前類中的所有屬性與 user 進行綁定@ConfigurationProperties(value = "user")public class User{           

複制

5.2 加載spring配置檔案

問題:如果有資訊需要寫道xml檔案中,想加載xml檔案怎麼辦

解決:使用@ImportResource加載外部配置檔案

5.3 使用注解方式添加元件

推薦使用全注解方式向Spring容器添加元件,@Configuration和@Bean

/** * Author: LuYi * Date: 2019/10/28 14:49 * Description: 描述 *///添加在類上,表示這個類是一個配置類,相當于spring配置檔案@Configurationpublic class SpringConfig { //标注在方法上,用來向容器中添加元件,将方法的傳回值添加到容器中,方法名作為bean的id @Bean public Address address(){ Address address = new Address(); address.setProvince("山東"); address.setCity("日照"); return address; }}           

複制

五、SpringBoot自動配置原理

1.執行流程

1.SpringBoot啟動時加載主配置類,使用@EnableAutoConfiguration開啟了自動配置功能

2.@EnableAutoConfiguration中使用了 @Import({AutoConfigurationImportSelector.class})向容器中添加了一些元件(自動配置類)

檢視AutoConfigurationImportSelector類中的selectImports方法,再點選getAutoConfigurationEntry方法中的`getCandidateConfigurations方法

通過getCandidateConfigurations中的loadFactoryNames方法加載到SpringFactory,

再通過classLoader加載META-INF/spring.factories的配置,從配置中擷取EnableAutoConfiguration(spring-boot-autoconfigure-2.1.9.RELEASE.jar)對應的值。

将這些自動配置類(xxxAutoConfiguration)添加到容器中

3.通過自動配置類完成自動配置功能。

2. 原理分析

以HttpEncodingAutoConfiguration為例,就是以前在web.xml中配置的CharacterEncodingFilter過濾器

//表示這是一個配置類,相當于以前編寫的Spring配置檔案@Configuration//啟用HttpProperties類的ConfigurationProperties功能,通過配置檔案為屬性注入值,并将其添加到容器中@EnableConfigurationProperties({HttpProperties.class})//當該應用是web應用時才生效@ConditionalOnWebApplication( type = Type.SERVLET)//必須包含CharacterEncodingFilter類才生效@ConditionalOnClass({CharacterEncodingFilter.class})//如果配置檔案中有spring.http.encoding選項則該配置生效,否則不生效。但是預設已經生效了@ConditionalOnProperty( prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true)public class HttpEncodingAutoConfiguration { private final Encoding properties;	 //将容器中的HttpProperties注入 public HttpEncodingAutoConfiguration(HttpProperties properties) { this.properties = properties.getEncoding(); } //将傳回的filter添加到容器中,作為bean @Bean //如果容器中沒有這個bean才會生效 @ConditionalOnMissingBean public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE)); return filter; } //從配置檔案中擷取指定的值,然後綁定到指定的屬性值@ConfigurationProperties( prefix = "spring.http")public class HttpProperties { private Charset charset; private Boolean force; private Boolean forceRequest; private Boolean forceResponse; private Map<Locale, Charset> mapping;           

複制

注意:

  • 根據目前情況進行判斷,決定配置類是否生産,如果不滿足條件自動配置就不會生效
  • 自動配置類xxAutoConfiguration的屬性是從對應的xxProperties類中擷取
  • xxProperties類中的資訊是通過配置檔案注入綁定的,可以通過配置檔案指定屬性的值

3.總結

  • SpringBoot在啟動時會加載大量的自動配置類
  • 通過自動配置了向容器中添加元件
  • 通過這些元件自動完成許多功能,進而簡化配置

可以通過開啟debug模式檢視自動配置類的比對情況

#開啟debug模式debug=true           

複制

六、Web開發

1.簡介

使用SpringBoot開發Web應用的步驟:

1.建立SpringBoot項目,添加對應的starter

2.在配置檔案中指定必要的少量配置

3.編寫業務代碼

Web開發的自動配置類WebMvcAutoConfiguration

2.關于靜态資源的映射

2.1 靜态資源的位置

檢視WebMvcAutoConfiguration——>addResourceHandlers()——>getStaticLocations()——>staticLocations

靜态資源的預設位置

"classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"           

複制

可以通過上面的檔案夾可以通路到靜态資源

也可以在配置檔案中自己指定可以通路的位置

# 指定靜态資源的位置 存放在根目錄下的public檔案夾中spring.resources.static-locations=classpath:/public           

複制

2.2 歡迎頁

檢視WebMvcAutoConfiguration—>welcomePageHandlerMapping()—>getWelcomePage()

将index.html頁面放到任意一個靜态資源檔案夾中的

2.3 網站圖示

檢視WebMvcAutoConfiguration—>内部類FaviconConfiguration—>faviconHandlerMapping

将favicon.ico放到靜态資源的任意檔案夾中即可

springboot面試題、以及Spring Boot 學習筆記完整教程 關注關注:麒麟改bug,擷取。