簡化Spring應用開發的一個框架;css
整個Spring技術棧的一個大整合;html
J2EE開發的一站式解決方案;java
一個功能:react
瀏覽器發送hello請求,服務器接受請求並處理,響應Hello World字符串;web
<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>
/** * @SpringBootApplication 來標註一個主程序類,說明這是一個Spring Boot應用 */ @SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) { // Spring應用啓動起來 SpringApplication.run(HelloWorldMainApplication.class,args); } }
@Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World!"; } }
<!-- 這個插件,能夠將應用打包成一個可執行的jar包;--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
將這個應用打成jar包,直接使用java -jar的命令進行執行;redis
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </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應用裏面的全部依賴版本; spring
Spring Boot的版本仲裁中心;apache
之後咱們導入依賴默認是不須要寫版本;(沒有在dependencies裏面管理的依賴天然須要聲明版本號)json
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
spring-boot-starter-==web==:瀏覽器
spring-boot-starter:spring-boot場景啓動器;幫咱們導入了web模塊正常運行所依賴的組件;
Spring Boot將全部的功能場景都抽取出來,作成一個個的starters(啓動器),只須要在項目裏面引入這些starter相關場景的全部依賴都會導入進來。要用什麼功能就導入什麼場景的啓動器
/** * @SpringBootApplication 來標註一個主程序類,說明這是一個Spring Boot應用 */ @SpringBootApplication public class HelloWorldMainApplication { public static void main(String[] args) { // Spring應用啓動起來 SpringApplication.run(HelloWorldMainApplication.class,args); } }
@SpringBootApplication: Spring Boot應用標註在某個類上說明這個類是SpringBoot的主配置類,SpringBoot就應該運行這個類的main方法來啓動SpringBoot應用;
@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的配置類;
標註在某個類上,表示這是一個Spring Boot的配置類;
@Configuration:配置類上來標註這個註解;
配置類 ----- 配置文件;配置類也是容器中的一個組件;
@EnableAutoConfiguration:開啓自動配置功能;
之前咱們須要配置的東西,Spring Boot幫咱們自動配置;
@EnableAutoConfiguration告訴SpringBoot開啓自動配置功能;
這樣自動配置才能生效;
@AutoConfigurationPackage @Import(EnableAutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {
@AutoConfigurationPackage:自動配置包
@Import(AutoConfigurationPackages.Registrar.class):
Spring的底層註解@Import,給容器中導入一個組件;導入的組件由AutoConfigurationPackages.Registrar.class;
==將主配置類(@SpringBootApplication標註的類)的所在包及下面全部子包裏面的全部組件掃描到Spring容器;==
@Import(EnableAutoConfigurationImportSelector.class);
給容器中導入組件
EnableAutoConfigurationImportSelector:導入哪些組件的選擇器;
將全部須要導入的組件以全類名的方式返回;這些組件就會被添加到容器中;
會給容器中導入很是多的自動配置類(xxxAutoConfiguration);就是給容器中導入這個場景須要的全部組件,並配置好這些組件;
有了自動配置類,免去了咱們手動編寫配置注入功能組件等的工做;
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
==Spring Boot在啓動的時候從類路徑下的META-INF/spring.factories中獲取EnableAutoConfiguration指定的值,將這些值做爲自動配置類導入到容器中,自動配置類就生效,幫咱們進行自動配置工做;==之前咱們須要本身配置的東西,自動配置類都幫咱們;
J2EE的總體整合解決方案和自動配置都在spring-boot-autoconfigure-1.5.9.RELEASE.jar;
IDE都支持使用Spring的項目建立嚮導快速建立一個Spring Boot項目;
選擇咱們須要的模塊;嚮導會聯網建立Spring Boot項目;
默認生成的Spring Boot項目;
主程序已經生成好了,咱們只須要咱們本身的邏輯
resources文件夾中目錄結構
static:保存全部的靜態資源; js css images;
templates:保存全部的模板頁面;(Spring Boot默認jar包使用嵌入式的Tomcat,默認不支持JSP頁面);可使用模板引擎(freemarker、thymeleaf);
application.properties:Spring Boot應用的配置文件;能夠修改一些默認設置;
SpringBoot使用一個全局的配置文件,配置文件名是固定的;
•application.properties
•application.yml
配置文件的做用:修改SpringBoot自動配置的默認值;SpringBoot在底層都給咱們自動配置好;
YAML(YAML Ain't Markup Language)
YAML A Markup Language:是一個標記語言
YAML isn't Markup Language:不是一個標記語言;
標記語言:
之前的配置文件;大多都使用的是 xxxx.xml文件;
YAML:以數據爲中心,比json、xml等更適合作配置文件;
YAML:配置例子
server: port: 8081
XML:
<server> <port>8081</port> </server>
k:(空格)v:表示一對鍵值對(空格必須有);
以空格的縮進來控制層級關係;只要是左對齊的一列數據,都是同一個層級的
server: port: 8081 path: /hello
屬性和值也是大小寫敏感;
k: v:字面直接來寫;
字符串默認不用加上單引號或者雙引號;
"":雙引號;不會轉義字符串裏面的特殊字符;特殊字符會做爲自己想表示的意思
name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
'':單引號;會轉義特殊字符,特殊字符最終只是一個普通的字符串數據
name: ‘zhangsan \n lisi’:輸出;zhangsan \n lisi
k: v:在下一行來寫對象的屬性和值的關係;注意縮進
對象仍是k: v的方式
friends: lastName: zhangsan age: 20
行內寫法:
friends: {lastName: zhangsan,age: 18}
配置文件
person: lastName: hello age: 18 boss: false birth: 2017/12/12 maps: {k1: v1,k2: 12} lists: - lisi - zhaoliu dog: name: 小狗 age: 12
javaBean:
/** * 將配置文件中配置的每個屬性的值,映射到這個組件中 * @ConfigurationProperties:告訴SpringBoot將本類中的全部屬性和配置文件中相關的配置進行綁定; * prefix = "person":配置文件中哪一個下面的全部屬性進行一一映射 * * 只有這個組件是容器中的組件,才能容器提供的@ConfigurationProperties功能; * */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
咱們能夠導入配置文件處理器,之後編寫配置就有提示了
<!--導入配置文件處理器,配置文件進行綁定就會有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
調整
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的屬性 | 一個個指定 |
鬆散綁定(鬆散語法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數據校驗 | 支持 | 不支持 |
複雜類型封裝 | 支持 | 不支持 |
配置文件yml仍是properties他們都能獲取到值;
若是說,咱們只是在某個業務邏輯中須要獲取一下配置文件中的某項值,使用@Value;
若是說,咱們專門編寫了一個javaBean來和配置文件進行映射,咱們就直接使用@ConfigurationProperties;
@Component @ConfigurationProperties(prefix = "person") @Validated public class Person { /** * <bean class="Person"> * <property name="lastName" value="字面量/${key}從環境變量、配置文件中獲取值/#{SpEL}"></property> * <bean/> */ //lastName必須是郵箱格式 @Email //@Value("${person.last-name}") private String lastName; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog;
@PropertySource:加載指定的配置文件;
/** * 將配置文件中配置的每個屬性的值,映射到這個組件中 * @ConfigurationProperties:告訴SpringBoot將本類中的全部屬性和配置文件中相關的配置進行綁定; * prefix = "person":配置文件中哪一個下面的全部屬性進行一一映射 * * 只有這個組件是容器中的組件,才能容器提供的@ConfigurationProperties功能; * @ConfigurationProperties(prefix = "person")默認從全局配置文件中獲取值; * */ @PropertySource(value = {"classpath:person.properties"}) @Component @ConfigurationProperties(prefix = "person") //@Validated public class Person { /** * <bean class="Person"> * <property name="lastName" value="字面量/${key}從環境變量、配置文件中獲取值/#{SpEL}"></property> * <bean/> */ //lastName必須是郵箱格式 // @Email //@Value("${person.last-name}") private String lastName; //@Value("#{11*2}") private Integer age; //@Value("true") private Boolean boss;
@ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效;
Spring Boot裏面沒有Spring的配置文件,咱們本身編寫的配置文件,也不能自動識別;
想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上
@ImportResource(locations = {"classpath:beans.xml"}) 導入Spring的配置文件讓其生效
不來編寫Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean> </beans>
SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式
一、配置類**@Configuration**------>Spring配置文件
二、使用**@Bean**給容器中添加組件
/** * @Configuration:指明當前類是一個配置類;就是來替代以前的Spring配置文件 * * 在配置文件中用<bean><bean/>標籤添加組件 * */ @Configuration public class MyAppConfig { //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名 @Bean public HelloService helloService02(){ System.out.println("配置類@Bean給容器中添加組件了..."); return new HelloService(); } }
${random.value}、${random.int}、${random.long} ${random.int(10)}、${random.int[1024,65536]}
person.last-name=張三${random.uuid} person.age=${random.int} person.birth=2017/12/15 person.boss=false person.maps.k1=v1 person.maps.k2=14 person.lists=a,b,c person.dog.name=${person.hello:hello}_dog person.dog.age=15
咱們在主配置文件編寫的時候,文件名能夠是 application-{profile}.properties/yml
默認使用application.properties的配置;
server: port: 8081 spring: profiles: active: prod --- server: port: 8083 spring: profiles: dev --- server: port: 8084 spring: profiles: prod #指定屬於哪一個環境
一、在配置文件中指定 spring.profiles.active=dev
二、命令行:
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
能夠直接在測試的時候,配置傳入命令行參數
三、虛擬機參數;
-Dspring.profiles.active=dev
springboot 啓動會掃描如下位置的application.properties或者application.yml文件做爲Spring boot的默認配置文件
–file:./config/
–file:./
–classpath:/config/
–classpath:/
優先級由高到底,高優先級的配置會覆蓋低優先級的配置;
SpringBoot會從這四個位置所有加載主配置文件;互補配置;
==咱們還能夠經過spring.config.location來改變默認的配置文件位置==
項目打包好之後,咱們可使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;指定配置文件和默認加載的這些配置文件共同起做用造成互補配置;
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
==SpringBoot也能夠從如下位置加載配置; 優先級從高到低;高優先級的配置覆蓋低優先級的配置,全部的配置會造成互補配置==
1.命令行參數
全部的配置均可以在命令行上進行指定
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系統屬性(System.getProperties())
4.操做系統環境變量
5.RandomValuePropertySource配置的random.*屬性值
==由jar包外向jar包內進行尋找;==
==優先加載帶profile==
6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
7.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件
==再來加載不帶profile==
8.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件
9.jar包內部的application.properties或application.yml(不帶spring.profile)配置文件
10.@Configuration註解類上的@PropertySource
11.經過SpringApplication.setDefaultProperties指定的默認屬性
全部支持的配置加載來源;
配置文件到底能寫什麼?怎麼寫?自動配置原理;
1)、SpringBoot啓動的時候加載主配置類,開啓了自動配置功能 ==@EnableAutoConfiguration==
2)、@EnableAutoConfiguration 做用:
利用EnableAutoConfigurationImportSelector給容器中導入一些組件?
能夠查看selectImports()方法的內容;
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);獲取候選的配置
SpringFactoriesLoader.loadFactoryNames() 掃描全部jar包類路徑下 META-INF/spring.factories 把掃描到的這些文件的內容包裝成properties對象 從properties中獲取到EnableAutoConfiguration.class類(類名)對應的值,而後把他們添加在容器中
==將 類路徑下 META-INF/spring.factories 裏面配置的全部EnableAutoConfiguration的值加入到了容器中;==
# Auto Configure org.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,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\ org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\ org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\ org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\ org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\ org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\ org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\ org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\ org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\ org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\ org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\ org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\ org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
每個這樣的 xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中;用他們來作自動配置;
3)、每個自動配置類進行自動配置功能;
4)、以HttpEncodingAutoConfiguration(Http編碼自動配置)爲例解釋自動配置原理;
@Configuration //表示這是一個配置類,之前編寫的配置文件同樣,也能夠給容器中添加組件 @EnableConfigurationProperties(HttpEncodingProperties.class) //啓動指定類的ConfigurationProperties功能;將配置文件中對應的值和HttpEncodingProperties綁定起來;並把HttpEncodingProperties加入到ioc容器中 @ConditionalOnWebApplication //Spring底層@Conditional註解(Spring註解版),根據不一樣的條件,若是知足指定的條件,整個配置類裏面的配置就會生效; 判斷當前應用是不是web應用,若是是,當前配置類生效 @ConditionalOnClass(CharacterEncodingFilter.class) //判斷當前項目有沒有這個類CharacterEncodingFilter;SpringMVC中進行亂碼解決的過濾器; @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) //判斷配置文件中是否存在某個配置 spring.http.encoding.enabled;若是不存在,判斷也是成立的 //即便咱們配置文件中不配置pring.http.encoding.enabled=true,也是默認生效的; public class HttpEncodingAutoConfiguration { //他已經和SpringBoot的配置文件映射了 private final HttpEncodingProperties properties; //只有一個有參構造器的狀況下,參數的值就會從容器中拿 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; }
根據當前不一樣的條件判斷,決定這個配置類是否生效?
一但這個配置類生效;這個配置類就會給容器中添加各類組件;這些組件的屬性是從對應的properties類中獲取的,這些類裏面的每個屬性又是和配置文件綁定的;
5)、全部在配置文件中能配置的屬性都是在xxxxProperties類中封裝者‘;配置文件能配置什麼就能夠參照某個功能對應的這個屬性類
@ConfigurationProperties(prefix = "spring.http.encoding") //從配置文件中獲取指定的值和bean的屬性進行綁定 public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
精髓:
1)、SpringBoot啓動會加載大量的自動配置類
2)、咱們看咱們須要的功能有沒有SpringBoot默認寫好的自動配置類;
3)、咱們再來看這個自動配置類中到底配置了哪些組件;(只要咱們要用的組件有,咱們就不須要再來配置了)
4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。咱們就能夠在配置文件中指定這些屬性的值;
xxxxAutoConfigurartion:自動配置類;
給容器中添加組件
xxxxProperties:封裝配置文件中相關屬性;
做用:必須是@Conditional指定的條件成立,纔給容器中添加組件,配置配裏面的全部內容才生效;
@Conditional擴展註解 | 做用(判斷是否知足當前指定條件) |
---|---|
@ConditionalOnJava | 系統的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在指定Bean; |
@ConditionalOnMissingBean | 容器中不存在指定Bean; |
@ConditionalOnExpression | 知足SpEL表達式指定 |
@ConditionalOnClass | 系統中有指定的類 |
@ConditionalOnMissingClass | 系統中沒有指定的類 |
@ConditionalOnSingleCandidate | 容器中只有一個指定的Bean,或者這個Bean是首選Bean |
@ConditionalOnProperty | 系統中指定的屬性是否有指定的值 |
@ConditionalOnResource | 類路徑下是否存在指定資源文件 |
@ConditionalOnWebApplication | 當前是web環境 |
@ConditionalOnNotWebApplication | 當前不是web環境 |
@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)