Spring boot 配置文件,配置註解詳解 (properties 和yml )

從其餘框架來看 咱們都有本身的配置文件, hibernate有hbm,mybatis 有properties, 一樣, Spring boot 也有全局配置文件。html

Springboot使用一個全局的配置文件,並且配置文件的名字是固定的。 有兩種java

  • application.properties
  • application.yml 

springboot 配置文件的做用是用來 修改SpringBoot自動配置的默認值;SpringBoot在底層都給咱們自動配置好; 像咱們Tomcat 啓動 默認配置端口是8080 . 若是要修改, 咱們就在這兩個文件的一種中來修改,react

  • YML (也叫YAML :  YAM Ain't  Markup Language)

      YAML Ain't Markup Language 這是一個遞歸寫法 ;web

  1. YAML  A Markup Language:是一個標記語言
  2. YAML   isn't Markup Language:不是一個標記語言;

標記語言: redis

   咱們之前用的配置文件,大多都使用 xxxx.xml  文件 ;spring

 YAML  : 是一種以數據爲中心的配置文件, 比json,xml  等更適合作配置文件 apache

舉個栗子:json

以 修改端口爲例 : 

yml : 

server:
  port: 8081

xml :
<server> <port>8081</port> </server>
 xml 配置 將太多的浪費在了標籤上面。

 yml 基本語法:

k:(空格)v:表示一對鍵值對(空格必須有);數組

 以  空格  的縮進來控制層級關係;只要是左對齊的一列數據,都是同一個層級的springboot

server:
    port: 8081
    path: /hello

屬性和值也是大小寫敏感;

值的寫法: 

  • 字面量:普通的值(數字,字符串,布爾)

 k: v:字面直接來寫;

字符串默認不用加上單引號或者雙引號;

"":雙引號;不會轉義字符串裏面的特殊字符;特殊字符會做爲自己想表示的意思 

    name:   "zhangsan \n lisi":輸出;zhangsan 換行  lisi

 '':單引號;會轉義特殊字符,特殊字符最終只是一個普通的字符串數據

name:   ‘zhangsan \n lisi’:輸出;zhangsan \n  lisi
  • 對象、Map(屬性和值)(鍵值對):

 k: v:在下一行來寫對象的屬性和值的關係;注意縮進

​        對象仍是k: v的方式

friends:
		lastName: zhangsan
		age: 20
行內寫法:

friends: {lastName: zhangsan,age: 18}
  •   數組(List、Set):

用 -  值表示數組中的一個元素

pets:
 - cat
 - dog
 - pig

行內寫法
pets: [cat,dog,pig]
  •   配置文件注入

javaBean :

能夠導入配置文件處理器依賴,之後編寫配置就會有代碼提示;

代碼展現配置文件注入屬性值 : 

 1 package com.example.webservice.bean;
 2 
 3 import org.springframework.boot.context.properties.ConfigurationProperties;
 4 import org.springframework.stereotype.Component;
 5 
 6 import java.util.Date;
 7 import java.util.List;
 8 import java.util.Map;
 9 
10 /**
11  *
12  * ConfigurationProperties(prefix ="person") 將本類中的全部屬性和配置文件中的相關配置進行綁定
13  * prefix ="person  表示對哪一個文件進行綁定
14  * Component 表示這是一個容器, 只有在容器中  ConfigurationProperties 才能使用
15 */
16 @Component
17 @ConfigurationProperties(prefix = "person")
18 public class Person {
19 
20      private String name;
21      private Integer age;
22      private boolean man;
23      private Date birth;
24      private Map<String,Object>map;
25      private List<Object>list ;
26      private Son son ;
27 
28 .....省略get/set  以及toString 方法 
29 
30 }
31 
32 
33 package com.example.webservice.bean;
34 
35 public class Son {
36 
37     private String name;
38     private Integer age ;
39 
40     public String getName() {
41         return name;
42     }
43 
44     public Integer getAge() {
45         return age;
46     }
47 
48     public void setName(String name) {
49         this.name = name;
50     }
51 
52     public void setAge(Integer age) {
53         this.age = age;
54     }
55 
56     @Override
57     public String toString() {
58         return "Son{" + "name='" + name + '\'' + ", age=" + age + '}';
59     }
60 }
61 
62 
63 properties文件綁定的寫法 
64 #註釋方法 Ctrl + /
65 person.name=爸爸
66 person.age=45
67 person.man=true
68 person.birth=2019/8/8
69 person.map.k1=h1
70 person.map.k2=h2
71 person.list=a,1,son
72 person.son.name=兒子
73 person.son,age=20
74 
75 
76 yml 文件綁定的寫法: 
77 
78 person:
79   name: 爸爸
80   age: 25
81   birth: 2018/2/8
82   man: true
83   list:
84     - a
85     - 2
86     - son
87   map: {key1:value1,key2:value2}
88   son:
89     name: 兒子
90     age: 5


測試類 :
在咱們的test 文件夾下 :
package com.example.webservice;

import com.example.webservice.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebserviceApplicationTests {

@Autowired
Person person;

@Test
public void contextLoads() { // 直接運行這個方法 ,而不是運行整個程序

System.out.println(person);

System.out.println("********************************************************");
}

 控制檯打印結果 (使用的 yml 配置文件)

properties配置文件在idea中默認utf-8可能會亂碼 。由於spring properties  默認是ASCII 碼 ,因此須要將properties  默認編碼改成UTP-8 ,再√上旁邊的 將其運行時轉換爲ASCII碼;再輸入中文就行了

都改爲utf-8 ,再輸入中文就行了。

  • @Value獲取值和@ConfigurationProperties獲取值比較

 |                                     | @ConfigurationProperties                | @Value |
| 功能                             |   批量注入配置文件中的屬性             | 一個個指定  |
| 鬆散綁定(鬆散語法) | 支持                                                  | 不支持    |
| SpEL                             | 不支持                                              | 支持     |
| JSR303數據校驗          | 支持                                                  | 不支持    |
| 複雜類型封裝               | 支持                                                  | 不支持    |

配置文件yml仍是properties他們都能獲取到值;
若是說,咱們只是在某個業務邏輯中須要獲取一下配置文件中的某項值,使用@Value;
若是說,咱們專門編寫了一個javaBean來和配置文件進行映射,咱們就直接使用@ConfigurationProperties;

  •  配置文件注入值數據校驗

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="name" value="字面量/${key}從環境變量、配置文件中獲取值/#{SpEL}"></property>
     * <bean/>
     */

   //name必須是郵箱格式
    @Email
    //@Value("${person.name}")
    private String name;
    //@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;
。。。。。get/set /toString 
  •  @PropertySource&@ImportResource&@Bean

  @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="name" value="字面量/${key}從環境變量、配置文件中獲取值/#{SpEL}"></property>
     * <bean/>
     */

   //name必須是郵箱格式
   // @Email
    //@Value("${person.name}")
    private String name;
    //@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的配置文件 ,下面這就是咱們一般的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.example.webservice.controller.Hello"></bean>
</beans>
SpringBoot推薦給容器中添加組件的方式;推薦使用全註解的方式

一、配置類**@Configuration**------>Spring配置文件

2、使用@Bean給容器中添加組件
/**
 * @Configuration:指明當前類是一個配置類;就是來替代以前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>標籤添加組件
 *
 */
@Configuration
public class MyAppConfig {

    //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置類@Bean給容器中添加組件了...");
        return new HelloService();
    }
}
  • 配置文件佔位符

 一、隨機數

1 ${random.value}、${random.int}、${random.long}
2 ${random.int(10)}、${random.int[1024,65536]}

 二、佔位符獲取以前配置的值,若是沒有能夠是用:指定默認值

 1 properties
 2 person.name=張三${random.uuid}
 3 person.age=${random.int}
 4 person.birth=2017/12/15
 5 person.boss=false
 6 person.maps.k1=v1
 7 person.maps.k2=14
 8 person.lists=a,b,c
// 若是沒有hello這個屬性, 則會直接輸出
${person.hello} , 若是加了
${person.hello:hello}_dog   則會直接賦值 輸出
hello_dog 
 9 person.dog.name=${person.hello:hello}_dog  

10 person.dog.age=15

三、Profile
一、多Profile文件
咱們在主配置文件編寫的時候,文件名能夠是   application-{profile}.properties/yml
springboot默認使用配置文件爲application.properties;

因此咱們在而後在application.properties配置文件中 激活自定義的環境配置文件就能夠了從application.properties 加載到application-dev.properties 文件了

在配置文件中指定 spring.profiles.active=dev

 二、yml支持多文檔塊方式

 1 server:
 2   port: 8081
 3 spring:
 4   profiles:
 5     active: prod  表示當前激活使用哪一個環境  --- 表示環境的分割 ,分紅不一樣的文檔塊。
 6 ---
 7 server:
 8   port: 8083
 9 spring:
10   profiles: dev
11 ---
12 server:
13   port: 8084
14 spring:
15   profiles: prod  #指定屬於哪一個環境

四、激活指定profile
​    一、在配置文件中指定  spring.profiles.active=dev
​    二、命令行:
​        java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
​        能夠直接在測試的時候,配置傳入命令行參數 ,打包好的項目運行的時候指定咱們的環境:

​    三、虛擬機參數; 在運行的時候 選擇Editor configrations

  -Dspring.profiles.active=dev    

五、配置文件加載位置

springboot 啓動會掃描如下位置的application.properties或者application.yml文件做爲Spring boot的默認配置文件
–file:./config/     文件路徑config目錄--->最高優先級
–file:./       文件路徑根目錄--->其次
–classpath:/config/ 類路徑config目錄--->再其次
–classpath:/     類路徑根目錄--->最低優先級

優先級由高到底,高優先級的配置會覆蓋低優先級的配置;
SpringBoot會從這四個位置所有加載主配置文件:互補配置;
咱們還能夠經過spring.config.location來改變默認的配置文件位置
項目打包好之後,咱們可使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;指定配置文件和默認加載的這些配置文件共同起做用造成互補配置;
 進入命令行 :

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties(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

7.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

8.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件

再來加載不帶profile

9.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件

10.jar包內部的application.properties或application.yml(不帶spring.profile)配置文件

11.@Configuration註解類上的@PropertySource

12.經過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的值加入到了容器中;

```properties
# 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
```
View Code

 

 每個這樣的  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類中封裝者‘;配置文件能配置什麼就能夠參照某個功能對應的這個屬性類

1 @ConfigurationProperties(prefix = "spring.http.encoding")  //從配置文件中獲取指定的值和bean的屬性進行綁定
2 public class HttpEncodingProperties {
3 
4    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

 

  • 精髓:

​   1)、SpringBoot啓動會加載大量的自動配置類**

​   2)、咱們看咱們須要的功能有沒有SpringBoot默認寫好的自動配置類;**

​   3)、咱們再來看這個自動配置類中到底配置了哪些組件;(只要咱們要用的組件有,咱們就不須要再來配置了)**

​   4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。咱們就能夠在配置文件中指定這些屬性的值;
xxxxAutoConfigurartion:自動配置類;
給容器中添加組件
xxxxProperties:封裝配置文件中相關屬性;


二、細節
一、@Conditional派生註解(Spring註解版原生的@Conditional做用)
做用:必須是@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屬性;來讓控制檯打印自動配置報告==**,這樣咱們就能夠很方便的知道哪些自動配置類生效;

 1 =========================
 2 AUTO-CONFIGURATION REPORT
 3 =========================
 4 Positive matches:(自動配置類啓用的)
 5 -----------------
 6    DispatcherServletAutoConfiguration matched:
 7       - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
 8       - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
 9         
10 Negative matches:(沒有啓動,沒有匹配成功的自動配置類)
11 -----------------
12    ActiveMQAutoConfiguration:
13       Did not match:
14          - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
15    AopAutoConfiguration:
16       Did not match:
17          - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)
相關文章
相關標籤/搜索