一、Spring Boot 入門
Spring Boot 來簡化Spring應用開發的一個框架,約定大於配置
Spring Boot 的底層用的就是Spring
訪問官網:spring.io 再點擊projects
1.背景
問題
J2EE笨重的開發,繁多的配置、低下的開發效率、複雜的部署流程,第三發技術集成難度大。
解決
「Spring全家桶」時代
Spring Boot -> J2EE一站式解決方案
Spring Cloud ->分布式整體解決方案
優點
快速創建獨立運行的Spring項目以及與主流框架集成
使用嵌套式的Servlet容器,應用無需打成WAR包
starters自動依賴與版本控制
大量的自動配置簡化開發,也可修改默認值
無需配置XML,無代碼生成,開箱即用
準成產環境的運行時應用監控
與雲計算的天然集成
微服務簡介
martinfowler.com
微服務:架構分格
一個應用應該是一組小型服務;可以通過http的方式進行互通
2.環境準備
jdk1.8
maven3.x
intellijIDEA
SpringBoot
MAVEN設置:給maven的setting.xml配置文件的profiles標籤添加
(F:\jsp\apache-maven-3.6.1-bin\apache-maven-3.6.1\conf)
<profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion></properties></profile>
2.IDEA的默認修改:
修改IDEA的默認maven ,具體看下面的博客https://blog.csdn.net/weixin_43034040/article/details/103835125
HelloWorld項目
瀏覽器發送hello請求,伺服器接收請求並處理,響應Hello World 字符串
第1步.創建一個maven工程(jar)
create new project ->maven->next
第2步.導入spring boot相關依賴
來到spring boot 官網
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>
第3步 .編寫一個主程序:啟動Spring Boot
package com.atguigu;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @SpringBootApplication 來標註一個主程序類,說明這是一個Spring Boot應用 */@SpringBootApplicationpublic class HelloWorldMainApplication { public static void main(String[] args) { //Spring應用啟動起來 SpringApplication.run(HelloWorldMainApplication.class,args); }}
第4步.編寫相關的Controller、Service
package com.atguigu.Controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello world"; }}
如果很多發那個發都是RESTAPI的方式,即發送數據給瀏覽器,而不是頁面跳轉,則@ResponseBody可以放在類外
@ResponseBody@Controllerpublic class HelloController { @RequestMapping("/hello") public String hello(){ return "Hello world"; }}
@ResponseBody、@Controller兩個合併:@RestController
//@ResponseBody//@Controller@RestControllerpublic class HelloController { @RequestMapping("/hello") public String hello(){ return "Hello world"; }}
第5步.運行並訪問
運行主程序
瀏覽器輸入:http://localhost:8080/hello
第6步.簡化部署
就算沒有裝tomcat環境也可以運行
a.導入插件:
將以下代碼添加到pom中
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>
b.打包
點擊Idea右邊的maven ->Lifecycle->package
此時maven介入進行打包,打包的地址為
Building jar:
G:\java\spring-boot-01-helloworld\target\spring-boot-01-helloworld-1.0-SNAPSHOT.jar
jar包內容:
BOOT-INF\classes:自己寫的類BOOT-INF\lib:maven依賴導入的,包含了tomcat
c.命令行運行
在jar包所在目錄下,命令行運行:java -jar spring-boot-01-helloworld-1.0-SNAPSHOT.jar
d.瀏覽器運行
瀏覽器輸入:http://localhost:8080/hello
3.HelloWorld項目解析
POM文件
父項目
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
查看spring-boot-starter-parent,它也有有父項目
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.9.RELEASE</version> <relativePath>../../spring-boot-dependencies</relativePath></parent>
查看spring-boot-dependencies,有定義了每一個依賴的版本,真正管理Spring Boot應用裡的所有應用版本
<properties> <!-- Dependency versions --> <activemq.version>5.14.5</activemq.version> <antlr2.version>2.7.7</antlr2.version> <appengine-sdk.version>1.9.59</appengine-sdk.version> <artemis.version>1.5.5</artemis.version> ... ... ...
導入starters啟動器
導入
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>
spring-boot-starter:spring-boot場景啟動器
spring-boot-starter-web:幫我們導入web模塊正常運行所依賴的組件。
starters啟動器
參考官網:
Spring Boot將所有的功能場景都抽取出來,做成一個個的starters(啟動器),只需要在項目裡引入這些starter相關的所有依賴都會導入進來。要用什麼就導入什麼場景啟動器。
主程序類,入口類
/** * @SpringBootApplication 來標註一個主程序類,說明這是一個Spring Boot應用 */@SpringBootApplicationpublic class HelloWorldMainApplication { public static void main(String[] args) { //Spring應用啟動起來,run()裡的類必須是@SpringBootApplication標註的類 SpringApplication.run(HelloWorldMainApplication.class,args); }}
@SpringBootApplication(即Spring Boot 應用)
進入SpringBootApplication查看發現是組合組件,如下:
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})})public @interface SpringBootApplication {
@SpringBootConfiguration
Spring Boot的配置類
標註在某個類上,表示是一個SpringBoot的配置類,
再點進去
發現@Configuration,這就是spring的配置註解。
@EnableAutoConfiguration
開啟自動配置功能;
以前需要配置的東西,現在spring boot幫我們自動配置,查看EnableAutoConfiguration有:
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
@AutoConfigurationPackage :自動配置包
進去查看:
有@Import({Registrar.class}),是Spring的底層註解,給容器導入自已組件
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
}
將主配置類(@SpringBootApplication標註的類)的所在包及下面所有子包裡面的所有組件掃描到Spring容器;
@Import({EnableAutoConfigurationImportSelector.class}):導入哪些選擇器,將所有需要導入的組件以全類名的方式返回;這些組件會被添加到容器中;會給容器導入非常多的(見下圖)自動配置類(xxxAutoConfigration);就是給容器中導入這個場景組要的所有組件,並配置包這些
extends AutoConfigurationImportSelector
public String[] selectImports(AnnotationMetadata annotationMetadata) {
4.使用Spring Initialier快速創建Spring Boot項目
選擇我們需要的模塊,嚮導會聯網創建Spring Boot項目。
步驟
選擇Spring Initialier
輸入Group、Artifact和 package
選擇功能模塊
刪除多餘的
失敗了,先跳過。
哈哈,我知道代替方法了,
1.使用https://start.spring.io/生成有錯誤的的代碼,錯誤之處在於版本,不知版本哪裡錯了,以後再說哦。
2。將版本改為1.5.9.RELEASE
出現問題:
Error:(3, 29) java: 程序包org.junit.jupiter.api不存在
解決:點擊test,導入
自動增加的內容
默認生成的Spring boot 項目:
主程序已經生成好了,我們只需要我們自己的邏輯
resources文件夾中目錄結構
static:所有的靜態資源;js,css,圖片
templates:保存所有的模板頁面;(Spring Boot默認jar包使用嵌套式的Tomcat,默認不支持JSP頁面);可以使用模板引擎
application.properties:Spring Boot 應用的配置文件
application.properties
想更改埠號:
application.properties文件裡添加:
server.port=8081
二、配置文件
1.配置文件
SpringBoot使用一個全局的配置文件,配置文件名是固定的。
application.properties
application.yml
配置文件的作用:修改SpringBoot自動配置的默認值;
YAML( YAML Ain`t Markup Language)
YAML A Markup Language:是一個標記語言
YAML isn`t Markup Language:不是一個標記語言
標記語言:
以前的配置文件大多是xxx.xml文件;
YAML:UI數據為中心,比json和xml更適合做配置文件
想更改埠號的三種文件方式
properties:
server.port=8081
YAML:
server : port : 8081
XML:
<server> <port>8081</port></server>
比較:XML造成大量文件空間的浪費,YAML非常簡潔
2.YAML語法
1.基本語法
k(空格):(空格) v 表示一對鍵值對以空格的縮進來控制層級關係;只要左對齊的一列數據,都是同一層級的。
server : port : 8081 path : /hello
屬性和值是大小寫敏感的
2.值的寫法
字面量 : 普通的值(數字,字符串,布爾)
k : v
字符串默認不加單引號或者雙引號;
雙引號:不會轉義字符串裡面的特殊字符單引號:會轉義
對象、Map(屬性和值)(鍵值對):
v是對象時
friends : lastName : zhangsan age : 20
或者行內寫法
friends : {lastName : zhangsan , age : 20}
數組(List、Set)
用 - 值表示數組中的一個元素
pets: - cat - dog - pig
或者行內寫法
pets: [cat,dog,pig]
3.@ConfigurationProperties
yaml和properties的寫法項目參考:G:\java\spring-boot-02-config-2
4.@Value
在spring基礎中
<bean> <property name="lastName" value="字面量、${key}配置文件或者環變量、#{SpEL}"></property></bean>
@Value就是上面代碼的value
@Value的使用
使用了@Value後就不需要寫@ConfigurationProperties
//@ConfigurationProperties(prefix = "person")public class Person { @Value("${person.last-name}") private String lastName; @Value("#{11*2}") private int age; #代表22 private Date birth; @Value("true") private boolean boss; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
5.@Conf…和@Value兩者比較
配置文件yml還是properties都可以,都是從全局配置文件中獲取值
簡單的用@Value複雜的用@ConfigurationProperties
@Conf…的數據效驗
@Component@ConfigurationProperties(prefix = "person")@Validated //數據效驗public class Person { @Email private String lastName;//必須輸入郵件類型的字符串
6.@PropertySource和@ImportResource
@PropertySource
作用:加載指定的配置文件;
@PropertySource(value = {"classpath:/person.properties"}) #指定了person.properties@Component@ConfigurationProperties(prefix = "person")public class Person { private String lastName;
@ImportResource
作用:導入Spring的配置文件,讓配置文件裡面的內容生效
自己添加的bean.xml,springboot才不鳥你,所以要連接起來@ImportResource標註在一個配置類上
不太好的寫法:
@ImportResource(locations = {"classpath:beans.xml"})@SpringBootApplicationpublic class SpringBoot02Config2Application { public static void main(String[] args) { SpringApplication.run(SpringBoot02Config2Application.class, args); }}
SpringBoot推薦:給容器中添加組件的方式,使用全註解的方式
配置類====配置文件使用@Bean給容器中添加組件@Configurationpublic class MyAppConfig { //將方法添加到容器中:容器中這個組件默認的id為方法名 @Bean public HelloService helloService(){ System.out.println("配置類@Bean給容器中添加組件了..."); return new HelloService(); }}
7.佔位符(數據插入)
1.隨機數
${random.int}
2.佔位符獲取之前配置的值
如果之前沒有配過該值,可以設置冒號:指定默認值
person.dog.name=${person.last-name}_dogperson.dog.name=${person.last-name:zhangsan}_dog #設置默認值
8.Profile(配置文件選擇)
1.多Profile文件
我們在主配置文件編寫的時候,文件名可以是 application-{profile}.properties/yml
從而實現動態切換。
默認是使用:application.properties
2.yml支持多文檔塊方式
server: port: 8081spring: profiles: active: dev---server: port: 8083spring: profiles: dev---server: port: 8084spring: profiles: prod
使用上面的
spring: profiles: active: dev
代碼進行切換
3.激活指定profile
注意:命令行裡激活方法和配置文件的種類無關創建不同的配置文件。
方式1:配置文件
在配置文件中指定:spring.profiles.active=dev
方式2:命令行
在命令行裡指定的配置文件:
--spring.profiles.active=dev
步驟
1.下拉,選擇edict configrations
2.program arguments輸入–spring.profiles.active=一種模式
方式2的另一種方法:項目編寫結束後,使用maven打包,命令行運行包
步驟
1.打包
2.運行
cd 到G:\java\spring-boot-02-config-2\target
命令行運行:
java -jar spring-boot-02-config-2-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
方式3:虛擬機參數
-Dspring.profiles.active=dev
步驟
1.下拉運行按鈕,選擇edict configrations
2.設置後運行即可
9.配置文件加載位置
1.優先級
spring boot啟動會掃描一下位置的application.properties或者application.yml文件作為Spring boot的默認配置文件
file:./config
file:./
classpath:/config/
classpath:/
以上是按照優先級從高到低的順序,所有位置的文件都會被加載,實現互補配置,高優先級配置內容覆蓋低優先級配置內容
我們可以通過spring.config.location來改變默認配置
優先級具體如下(高->低):
2.默認位置更改
使用spring.config.location
是在項目打包好後,我們可以使用命令行參數的形式,啟動項目的時候來制定配置文件的;指定的配置的文件和默認加載的配置文件會共同起作用,形成互補配置。
我試過不共存啊?????????????????
java -jar spring-boot-02-config02-0.0.1-SNAPSHOT.jar --spring.config.location=C:\Users\Willian\Desktop\application.properties
10.外置配置加載順序
1.命令行Spring Boot Reference Guide1.命令行
java -jar spring-boot-02-config02-0.0.1-SNAPSHOT.jar --server.port=8087
多個參數用空格隔開;–配置值=值
當jar壓縮包同路徑下有application.properties時,會自動發運行加載
2.來自java:comp/env的NDI屬性
3.Java系統變量 (System.getProperties()).
4.作業系統變量
5.RandomValuePropertySource 配置的 random.*屬性值
先加載帶profile
6.jar包外部的application-{profile}.properties或application.yaml(帶spring.profile)配置文件
7.jar包內部的application-{profile}.properties或application.yaml(帶spring.profile)配置文件
再來加載帶不帶profile
8.jar包外部的application.properties或application.yaml(不帶spring.profile)配置文件
9.jar包內部的application.properties或application.yaml(不帶spring.profile)配置文件
10.@Configration註解類上的@PropertySource
11.通過SpringApplication.setDefaultProperties指定默認屬性
11.自動配置原理
配置文件到底寫什麼?怎麼寫?自動配置原理;
配置參照
自動配置原理
注意是1.5.9版本。2.2.0無EnableAutoConfigurationImportSelector
springboot啟動的時候,加載主配置類,而且開啟制動配置功能@EnableAutoConfiguration
用EnableAutoConfigurationImportSelector給容器中導入一些組件
查看selectImports()方法
List configurations = this.getCandidateConfigurations(annotationMetadata, attributes);獲取候選的配置
SpringFactoriesLoader.loadFactoryNames()
掃描jar包類路徑下的META-INF/spring.factories,
把掃描到的這些文件的內容包裝成properties的對象
從properties中獲取到EnableAutoConfiguration.class類(類名)對應的值,讓後把他們添加到容器中
所以一句話就是
將類路徑下的 META-INF/spring.factories裡面的配置的所有EnableAutoConfiguration值加入到容器中
每一個xxxAutoConfiguration類都是容器的一個組件,都加入到容器中,用他們來做自動配置
每一個自動配置類進行自動配置類功能;以HttpEncodingAutoConfiguration為例
根據當前不同的條件判斷,決定這個配置類是否生效
一旦這個配置類生效,這個配置類就會給容器添加各種組件;這些組件的屬性是從對應的properties類中獲取,這些類裡面的每個屬性又是和配置文件綁定的;
@Configuration //這是一個配置類@EnableConfigurationProperties({HttpEncodingProperties.class})//下有解釋,把HttpEncodingProperties加入到ioc容器中@ConditionalOnWebApplication//@Conditional是spring底層。指定條件配置生效;此處判斷是否為web應用,如果是,生效@ConditionalOnClass({CharacterEncodingFilter.class})//判斷當前項目有無該類,CharacterEncodingFilter是springMVC中進行亂碼解決的過濾器@ConditionalOnProperty(//判斷配置文件是否存在某個配置spring.http.encoding,不配置或配置返回true prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true)//如果上面的條件都成立,則執行下面類public class HttpEncodingAutoConfiguration { //他已經和SpringBoot的配置文件映射了 private final HttpEncodingProperties properties; //只有一個有參構造器的情況下,參數的值就會從容器中拿@EnableConfigurationProperties public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) { this.properties = properties; } @Bean //為容器添加一個組件,組件的某些值需要在properties中獲取 @ConditionalOnMissingBean({CharacterEncodingFilter.class}) public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE)); return filter; }
@EnableConfigurationProperties({HttpEncodingProperties.class})
啟用指定類(HttpEncodingProperties)的EnableConfigurationProperties功能
所有在配置文件中能配置的屬性都是在xxxProperties類中封裝著;
進入HttpEncodingProperties查看有
@ConfigurationProperties( prefix = "spring.http.encoding" //從配置文件中獲取指定值和bean的屬性)public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
精髓:
SpringBoot啟動會加載大量的配置類
我們看我們需要的功能有沒有SpringBoot默認寫好的自動配置類
再來坑自動配置類中配置 哪些組件;只要我們要用的組件有,我們就不需要配置
給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值
xxxAutoConfigration:自動配置類
給容器添加組件(裡面有@Bean)
xxxProperties:封裝配置文件中的相關屬性
細節:conditional
@Conditional是指定條件成立
自動配置類必須在一定條件下才生效怎麼知道哪些類生效?
10.生效配置類查看
可以通過配置debug=true屬性
三、日誌
1.日誌框架
小張用System.out.println("");將關鍵數據列印在控制臺;現在去掉,卸載文件裡
用框架記錄運行信息;日誌框架,zhanglogging.jar
升級,異步,自動…,zhanglogging-good.jar
更換框架,修改API,zhanglogging-perfect.jar
參考JDBC–資料庫驅動;寫一個統一的接口層
市面上的日誌框架
JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j、、
挑選
日誌門面:SLF4J
日誌實現:Logback
SpringBoot:底層是Spring框架,Spring架構默認是JCL;
SpringBoot選用SLF4J和Logback
2.SLF4j使用
1.如何在系統中使用SLF4j
日誌記錄方法的調用,不應該直接調用日誌的實現類,而是調用日誌抽象層裡面的方法
官網:SLF4J
複製下面代碼
import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); }}
每一個日誌的實現框架都有知己的配置文件。使用slf4j以後,配置文件還是做成日誌實現框架的配置文件
2.遺留問題
如果有個系統a,使用的是slf4j+logback,它整合了Spring、Hibernate、MyBatis…,他們用了不同的日誌框架,如何統一?
統一日誌記錄,即使是別的框架,和我一起統一進行輸出。
核心總結:如何讓系統中所有的日誌都統一到slf4j?
1.將系統中的其他日誌框架先排除出去;2.用中間包來替換原來的日誌框架3.再來導入slf4j其他的實現
3.SpringBoot日誌關係
總結:
springboot底層也是使用slf4j+logback方式進行日誌記錄springboot也把其他的日誌替換成slf4j雖然表面上用的是其他的包,但是其他包的內部引用的還是slf4j
如果我們要引入其他框架,IDing要把這個框架的默認日誌依賴移除掉
可以發現springboot2.0之前的版本,springboot是直接排除(exclusions)底層Spring的comons-logging(JCL)框架
在springboot2.0之後用的是Spring5,Spring5用的是slf4j,所以就無需排除了
3.日誌使用
1.默認配置
SpringBoot 默認幫我們配置好了日誌;import org.slf4j.Logger;import org.slf4j.LoggerFactory;package com.atguigu.springboot;
import org.junit.jupiter.api.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass SpringBoot03LoggingApplicationTests { //記錄器 Logger logger = LoggerFactory.getLogger(getClass()); @Test void contextLoads() { //日誌級別 //又低到高 //可以調整輸出的日誌級別 logger.trace("這是trace日誌..."); logger.debug("這是debug日誌..."); //默認是info級別 logger.info("這是info日誌..."); logger.warn("這是warn日誌..."); logger.error("這是error日誌..."); }}
更改默認級別:
logging.level.com.atguigu=trace #com.atguigu是指定地方#當前項目下生成logging.file.name=springboot.log#G盤下生成#logging.file.name=G:/springboot.log#根目錄(G盤)下生成#logging.file.path=/spring/log#控制臺輸出的日誌格式logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS}[%thead] %-5level %logger{50} - %msg%n}#指定文件中的日誌輸出格式logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS}[%thead] === %-5level === %logger{50} === %msg%n}
日誌輸出格式:
時間:%d{yyyy-MM-dd HH:mm:ss.SSS}
線程名:%thead
字符寬度限制:%-5 表示從左顯示5個字符寬度
長度分割:%logger{50} 表示以50個字符為單位進行分割
日誌消息:%msg
換行:%n
2.指定配置
官方教程:
Spring Boot Reference Guide
給類路徑下放上每個日誌框架自己的配置文件即可;Springboot就不適用他默認配置的了
logback.xml:直接被日誌框架識別,相當於繞過springboot,
建議使用logback-spring.xml,可以使用下面的配置,指定某個配置只在某個環境下生效
<springProfile name="staging"> <!-- configuration to be enabled when the "staging" profile is active --></springProfile><springProfile name="dev, staging"> <!-- configuration to be enabled when the "dev" or "staging" profiles are active --></springProfile><springProfile name="!production"> <!-- configuration to be enabled when the "production" profile is not active --></springProfile
四、Spring Boot與Web開發
1.SpringBoot對靜態資源的映射規則
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } }
1)、所有/Webjars/都是從classpath:/META-INF/resources/webjars/**找資源
Webjars:以jar包的方式引入靜態資源
https://www.webjars.org/www.webjars.org
再在項目裡導入
訪問jquery.js
localhost:8080/webjars/jquery/3.3.1/jquery.js
至此,全文完畢,碼字不易(快兩萬字了。。。),能看到這裡的小夥伴都是積極又認真的同學,幫忙點個關注分享下再走吧,多謝!