Java - 框架之 SpringBoot 攻略day01
Spring-Boot 攻略 day01
spring-boot
一. 基本配置加運行
1. 導(dǎo)入配置文件(pom.xml 文件中)
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.9.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
2. Application.java
@SpringBootApplicationpublicclassHelloApplication{publicstaticvoid main(String[] args){SpringApplication.run(HelloApplication.class, args);}}
3. Controller.java
/*@RestController 可以代替 @ResponseBody 和 @Controller*/@ResponseBody@Controllerpublicclass h1Controller {@RequestMapping("/hello")publicString t1(){return"Hello!";}}
4. 直接運行 Application 中的代碼,頁面訪問 http://localhost:8080/hello 就會看到 Hello!。
5. 打包 jar 包,在 pom.xml 配置文件中添加:
<!-- 這個插件,可以將應(yīng)用打包成一個可執(zhí)行的jar包;--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
6.運行:
java -jar jar包名
二. SpringBoot( pom.xml )文件講解
1. 依賴包:
都存放在 pom.xml 文件 -> spring-boot-starter-parent -> spring-boot-dependedcies 中
2. 啟動器
spring-boot-starter: Spring-Boot 場景啟動器。
比如上面的 **spring-boot-starter-web**就幫我們導(dǎo)入了有關(guān)web項目的啟動器, 所以需要什么場景的starter(啟動器),只需要導(dǎo)入相關(guān)依賴即可。
<artifactId>spring-boot-starter-web</artifactId>
三. 主程序(主入口)類
1. 注解
@SpringBootApplication :標(biāo)注在某個類上說明這個類是 SpringBoot 的主配置類,SpringBoot 可以運行這個類的 main 方法來啟動服務(wù)。
@SpringBootApplicationpublicclassHelloApplication{publicstaticvoid main(String[] args){SpringApplication.run(HelloApplication.class, args);}}
@SpringBootConfiguration :Spring Boot的配置類;
@Configuration :配置類標(biāo)注這個注解(配置文件;配置類也是容器中的一個組件;@Component)
@EnableAutoConfiguration :開啟自動配置功能;
@AutoConfigurationPackage :自動配置包;
@Import(EnableAutoConfigurationImportSelector.class) : 給容器中導(dǎo)入組件;
四. 使用 Spring Initializer 快速創(chuàng)建 Spring Boot 項目
1. 創(chuàng)建 Spring Initializer 項目,并選擇需要使用的模塊。
2. resources 文件夾中目錄結(jié)構(gòu)
- static : 靜態(tài)資源
- templates :模板頁面
- application.properties : SpringBoot 應(yīng)用的配置文件
五. 配置文件(兩者都可配置,寫法不同)
1. application.properties
- 寫法:
server.port=8081
2. application.yml (默認(rèn)沒有,需手動創(chuàng)建到 resources 文件下)
- 寫法
server:port:8081
3. YMAL 基本語法
- 以空格縮進(jìn)
server:port:8081
-
值的寫法
- 字面量:k: v 的方式來寫(注意有個空格在:的后面)
?
"" :雙引號不會轉(zhuǎn)義特殊字符
'' : 單引號會轉(zhuǎn)移特殊字符(轉(zhuǎn)義為字符串)
?
- 字面量:k: v 的方式來寫(注意有個空格在:的后面)
-
對象,Map 寫法
-
k: v 與上面寫法一致
server:port:8081
-
行內(nèi)表示:
server:{port:8081}
-
-
數(shù)組 (List, Set)
Person:- p1- p2- p3
4. 配置文件的注入
注意:這個配置順序要寫在單元測試配置之前
<!--導(dǎo)入配置文件處理器,配置文件進(jìn)行綁定就會有提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processo</artifactId><optional>true</optional></dependency>
一. yaml 配置
- application.yml
lastname:張三age:11isBoy:trueDate:2019/4/19maps:{k1: v1, k2:59}lists:- li1- li2dog:name:黑狗age:1
- Person.java
/** 將配置文件中配置的每一個屬性值,映射到這個組件中* @ConfigurationProperties:告訴 SpringBoot 將當(dāng)前類中的所有屬性與 配置文件中的配置進(jìn)行幫定* prefix = "person" : 配置文件中哪個下面的所有屬性進(jìn)行映射** 只有這個組件是容器中的組件,才能提供 @ConfigurationProperties 中的功能,也就是需要加上:@Component* */@Component@ConfigurationProperties(prefix ="person")publicclassPerson{privateString lastName;privateInteger age;privateBoolean isBoy;privateDate birthday;privateMap<Object,Object> maps;privateList<Object> lists;privateDog dog;}
- Dog.java
publicclassDog{privateString name;privateInteger age;}
- Test 單元測試
@AutowiredPerson person;@Testpublicvoid contextLoads(){System.out.println(person);}
二. properties 配置 ( application.properties )
注意:使用這個配置會有編碼問題,解決如下( idea ):
settings -> File Encodings 配置下:
Default encoding for properties files: 設(shè)置為 UTF-8
勾選:Transparent native-to-ascii conversion 這個選項
- application.properties 文件
# 配置 Person 的值person.last-name=張三person.age=11person.birthday=2019/4/19person.isBoy=trueperson.maps.k1=v1person.maps.k2=59person.lists=p1,p2,p3person.dog.name=大黑狗person.dog.age=2
- 剩余配置如上
三. @ConfigurationProperties 與 @Value
| 比較 | @ConfigurationProperties | @Value |
|---|---|---|
| 功能 | 批量注入配置文件中的屬性 | 一個個指定 |
| 松散綁定(松散語法) | 支持 | 不支持 |
| SpEL | 不支持 | 支持 |
| JSR303數(shù)據(jù)校驗 | 支持 | 不支持 |
| 復(fù)雜類型封裝 | 支持 | 不支持 |
- 松散綁定 :如果遇到 last-name 可以寫成 lastName,也就是帶有 - 或 _ 的后一個字母可用大寫
- SpEL : 語法解析,如 ${1*19} , @Value 就可以解析
- JSR303數(shù)據(jù)校驗 : 內(nèi)置的 @Eamil 等可以進(jìn)行數(shù)據(jù)的校驗,詳細(xì)請看下文
- 復(fù)雜類型封裝 :如 Map 等復(fù)雜類型 @Value 是無法解析的(List可以解析),會報錯
@Component//@ConfigurationProperties(prefix = "person")@ValidatedpublicclassPerson{// @Value("${person.last-name}")@Email// 這里 lastName 必須是郵箱格式privateString lastName;@Value("#{1*10}")// 可進(jìn)行邏輯操作privateInteger age;privateBoolean isBoy;privateDate birthday;privateMap<Object,Object> maps;privateList<Object> lists;privateDog dog;}
四. @PropertySource & @ImportResource & @Bean
@PropertySource:加載指定的配置文件;
/**** @PropertySource : 可以指定到去哪個文件加載配置*/@PropertySource(value ={"classpath:person.properties"})@Component@ConfigurationProperties(prefix ="person")//@ValidatedpublicclassPerson{/*** <bean class="Person">* <property name="lastName" value="字面量/${key}從環(huán)境變量、配置文件中獲取值/#{SpEL}"></property>* <bean/>*///lastName必須是郵箱格式// @Email//@Value("${person.last-name}")privateString lastName;//@Value("#{11*2}")privateInteger age;//@Value("true")privateBoolean boss;}
@ImportResource:導(dǎo)入Spring的配置文件,讓配置文件里面的內(nèi)容生效;
Spring Boot里面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進(jìn)來;@ImportResource標(biāo)注在一個配置類上
@ImportResource(locations ={"classpath:beans.xml"})導(dǎo)入Spring的配置文件讓其生效
使用XML文件加載配置(beans.xml)
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><beanid="helloService"class="com.atguigu.springboot.service.HelloService"></bean></beans>
SpringBoot推薦給容器中添加組件的方式:使用全注解
1、配置類@Configuration------>Spring配置文件
2、使用@Bean給容器中添加組件
- Service.java
// @Configuration :指明當(dāng)前類為配置類,用來替代 Spring 配置文件@ConfigurationpublicclassMyAppConfig{// @Bean :將方法的返回值添加到容器中,容器中這個組件的默認(rèn)id就是方法名@BeanpublicHelloService helloService(){returnnewHelloService();}}
- 單元測試類
@AutowiredApplicationContext ioc;@Testpublicvoid testHelloService(){System.out.println("執(zhí)行配置文件...");boolean b = ioc.containsBean("helloService");System.out.println(b);}
五. 配置文件占位符
1、隨機數(shù)
${random.value}、${random.int}、${random.long}${random.int(10)}、${random.int[1024,65536]}
2、占位符獲取之前配置的值,如果沒有可以是用:指定默認(rèn)值
person.last-name=張三${random.uuid}person.age=${random.int}person.birth=2017/12/15person.boss=falseperson.maps.k1=v1person.maps.k2=14person.lists=a,b,cperson.dog.name=${person.hello:hello}_dogperson.dog.age=15
六. Profile
1、多Profile文件
我們在主配置文件編寫的時候,文件名可以是 application-{profile}.properties/yml
默認(rèn)使用application.properties的配置;
2、yml支持多文檔塊方式
server:port:8081spring:profiles:active: prod---server:port:8083spring:profiles: dev---server:port:8084spring:profiles: prod #指定屬于哪個環(huán)境
3、激活指定profile
? 1、在配置文件中指定 spring.profiles.active=dev
? 2、命令行:
? java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
? 可以直接在測試的時候,配置傳入命令行參數(shù)
? 3、虛擬機參數(shù);
? -Dspring.profiles.active=dev
七、配置文件加載位置
springboot 啟動會掃描以下位置的application.properties或者application.yml文件作為Spring boot的默認(rèn)配置文件
–file:./config/
–file:./
–classpath:/config/
–classpath:/
優(yōu)先級由高到底,高優(yōu)先級的配置會覆蓋低優(yōu)先級的配置;
SpringBoot會從這四個位置全部加載主配置文件;互補配置;
==我們還可以通過spring.config.location來改變默認(rèn)的配置文件位置==
項目打包好以后,我們可以使用命令行參數(shù)的形式,啟動項目的時候來指定配置文件的新位置;指定配置文件和默認(rèn)加載的這些配置文件共同起作用形成互補配置;
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
八、外部配置加載順序
==SpringBoot也可以從以下位置加載配置; 優(yōu)先級從高到低;高優(yōu)先級的配置覆蓋低優(yōu)先級的配置,所有的配置會形成互補配置==
1.命令行參數(shù)
所有的配置都可以在命令行上進(jìn)行指定
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
多個配置用空格分開; --配置項=值
2.來自java:comp/env的JNDI屬性
3.Java系統(tǒng)屬性(System.getProperties())
4.操作系統(tǒng)環(huán)境變量
5.RandomValuePropertySource配置的random.*屬性值
==由jar包外向jar包內(nèi)進(jìn)行尋找;==
==優(yōu)先加載帶profile==
6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
7.jar包內(nèi)部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
==再來加載不帶profile==
8.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
9.jar包內(nèi)部的application.properties或application.yml(不帶spring.profile)配置文件
10.@Configuration注解類上的@PropertySource
11.通過SpringApplication.setDefaultProperties指定的默認(rèn)屬性
所有支持的配置加載來源;
參考官方文檔
8、自動配置原理
配置文件到底能寫什么?怎么寫?自動配置原理;
配置文件能配置的屬性參照
1、自動配置原理:
1)、SpringBoot啟動的時候加載主配置類,開啟了自動配置功能 ==@EnableAutoConfiguration==
2)、@EnableAutoConfiguration 作用:
-
利用EnableAutoConfigurationImportSelector給容器中導(dǎo)入一些組件?
-
可以查看selectImports()方法的內(nèi)容;
-
List configurations = getCandidateConfigurations(annotationMetadata, attributes);獲取候選的配置
SpringFactoriesLoader.loadFactoryNames()掃描所有jar包類路徑下 META-INF/spring.factories把掃描到的這些文件的內(nèi)容包裝成properties對象從properties中獲取到EnableAutoConfiguration.class類(類名)對應(yīng)的值,然后把他們添加在容器中
?
-
==將 類路徑下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;==
# 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.CloudAutoConfiguration,\org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,...
每一個這樣的 xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中;用他們來做自動配置;
3)、每一個自動配置類進(jìn)行自動配置功能;
4)、以HttpEncodingAutoConfiguration(Http編碼自動配置)為例解釋自動配置原理;
@Configuration//表示這是一個配置類,以前編寫的配置文件一樣,也可以給容器中添加組件@EnableConfigurationProperties(HttpEncodingProperties.class)//啟動指定類的ConfigurationProperties功能;將配置文件中對應(yīng)的值和HttpEncodingProperties綁定起來;并把HttpEncodingProperties加入到ioc容器中@ConditionalOnWebApplication//Spring底層@Conditional注解(Spring注解版),根據(jù)不同的條件,如果滿足指定的條件,整個配置類里面的配置就會生效; 判斷當(dāng)前應(yīng)用是否是web應(yīng)用,如果是,當(dāng)前配置類生效@ConditionalOnClass(CharacterEncodingFilter.class)//判斷當(dāng)前項目有沒有這個類CharacterEncodingFilter;SpringMVC中進(jìn)行亂碼解決的過濾器;@ConditionalOnProperty(prefix ="spring.http.encoding", value ="enabled", matchIfMissing =true)//判斷配置文件中是否存在某個配置 spring.http.encoding.enabled;如果不存在,判斷也是成立的//即使我們配置文件中不配置pring.http.encoding.enabled=true,也是默認(rèn)生效的;publicclassHttpEncodingAutoConfiguration{//他已經(jīng)和SpringBoot的配置文件映射了privatefinalHttpEncodingProperties properties;//只有一個有參構(gòu)造器的情況下,參數(shù)的值就會從容器中拿publicHttpEncodingAutoConfiguration(HttpEncodingProperties properties){this.properties = properties;}@Bean//給容器中添加一個組件,這個組件的某些值需要從properties中獲取@ConditionalOnMissingBean(CharacterEncodingFilter.class)//判斷容器沒有這個組件?沒有才加載publicCharacterEncodingFilter characterEncodingFilter(){CharacterEncodingFilter filter =newOrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));return filter;}
根據(jù)當(dāng)前不同的條件判斷,決定這個配置類是否生效?
一但這個配置類生效;這個配置類就會給容器中添加各種組件;這些組件的屬性是從對應(yīng)的properties類中獲取的,這些類里面的每一個屬性又是和配置文件綁定的;
5)、所有在配置文件中能配置的屬性都是在xxxxProperties類中封裝者‘;配置文件能配置什么就可以參照某個功能對應(yīng)的這個屬性類
@ConfigurationProperties(prefix ="spring.http.encoding")//從配置文件中獲取指定的值和bean的屬性進(jìn)行綁定publicclassHttpEncodingProperties{publicstaticfinalCharset DEFAULT_CHARSET =Charset.forName("UTF-8");
精髓:
? 1)、SpringBoot啟動會加載大量的自動配置類
? 2)、我們看我們需要的功能有沒有SpringBoot默認(rèn)寫好的自動配置類;
? 3)、我們再來看這個自動配置類中到底配置了哪些組件;(只要我們要用的組件有,我們就不需要再來配置了)
? 4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值;
xxxxAutoConfigurartion:自動配置類;
給容器中添加組件
xxxxProperties:封裝配置文件中相關(guān)屬性;
2、細(xì)節(jié)
1、@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必須是@Conditional指定的條件成立,才給容器中添加組件,配置配里面的所有內(nèi)容才生效;
| @Conditional擴展注解 | 作用(判斷是否滿足當(dāng)前指定條件) |
|---|---|
| @ConditionalOnJava | 系統(tǒng)的java版本是否符合要求 |
| @ConditionalOnBean | 容器中存在指定Bean; |
| @ConditionalOnMissingBean | 容器中不存在指定Bean; |
| @ConditionalOnExpression | 滿足SpEL表達(dá)式指定 |
| @ConditionalOnClass | 系統(tǒng)中有指定的類 |
| @ConditionalOnMissingClass | 系統(tǒng)中沒有指定的類 |
| @ConditionalOnSingleCandidate | 容器中只有一個指定的Bean,或者這個Bean是首選Bean |
| @ConditionalOnProperty | 系統(tǒng)中指定的屬性是否有指定的值 |
| @ConditionalOnResource | 類路徑下是否存在指定資源文件 |
| @ConditionalOnWebApplication | 當(dāng)前是web環(huán)境 |
| @ConditionalOnNotWebApplication | 當(dāng)前不是web環(huán)境 |
| @ConditionalOnJndi | JNDI存在指定項 |
自動配置類必須在一定的條件下才能生效;
我們怎么知道哪些自動配置類生效;
==我們可以通過啟用 debug=true屬性;來讓控制臺打印自動配置報告==,這樣我們就可以很方便的知道哪些自動配置類生效;
=========================AUTO-CONFIGURATION REPORT=========================Positive matches:(自動配置類啟用的)-----------------DispatcherServletAutoConfiguration matched:-@ConditionalOnClass found required class'org.springframework.web.servlet.DispatcherServlet';@ConditionalOnMissingClass did not find unwanted class(OnClassCondition)-@ConditionalOnWebApplication(required) found StandardServletEnvironment(OnWebApplicationCondition)Negative matches:(沒有啟動,沒有匹配成功的自動配置類)-----------------ActiveMQAutoConfiguration:Did not match:-@ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory','org.apache.activemq.ActiveMQConnectionFactory'(OnClassCondition)AopAutoConfiguration:Did not match:-@ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect','org.aspectj.lang.reflect.Advice'(OnClassCondition)
轉(zhuǎn)載于:https://www.cnblogs.com/chaoqi/p/10739739.html
總結(jié)
以上是生活随笔為你收集整理的Java - 框架之 SpringBoot 攻略day01的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 外国喜剧,一个丑女找一个侏儒变成了美女,
- 下一篇: 请问移动wifi要怎么弄 多少钱啊一个月