(五)SpringBoot2.0基礎之配置文件

在這裏插入圖片描述

知其然 知其所以然

創作不易 求點贊👍 求關注❤️ 求分享👥

絮叨

上一篇呢我們講解了日誌的一些基礎和SpringBoot中的日誌,日誌作爲程序中不可或缺的一部分也是非常重要的,這一篇呢我們來看一下SpringBoot的配置文件,加載順序和配置的原理。

正文

配置文件

YAML

SpringBoot使用一個全局的配置文件,配置文件名是固定的:application.properties和application.yml。在這裏,可以修改SpringBoot自動配置的值。
YAML是一個可讀性高,用來表達數據序列化的格式。可以簡單表達清單、散列表,標量等數據形態。它使用空白符號縮進和大量依賴外觀的特色,可以省略大量的前綴。
YAML:

server:
  port: 8080
  url: 192.168.1.1

XML:

<server>
    <port>8080</port>
    <url>192.168.1.1</url>
</server>

在SpringBoot應用中,大部分都是用yml當作配置文件,關於yaml的語法這裏不做具體講解,大家可以自行百度。

配置文件注入值
  • @Value註解注入將配置文件中的屬性讀取出來,並賦值給被註解標記的字段上。

    people:
      name: zhangsan
      age: 18
      addr: China
    
    package com.springboot.springinitializr.helloworld.bean;
    
    @SpringBootTest
    public class PeopleTest {
    
        @Value("${people.name}")
        private String name;
        @Value("${people.age}")
        private int age;
        @Value("${people.addr}")
        private String addr;
    
        @Test
        public void test() {
            String m_name = name;
            int m_age = age;
            String m_addr = addr;
            System.out.println("m_name --> " + m_name);
            System.out.println("m_age --> " + m_age);
            System.out.println("m_addr --> " + m_addr);
        }
    }
    

    在這裏插入圖片描述

  • @ConfigurationProperties註解注入批量注入配置文件中的屬性。告訴SpringBoot將本類中的所有屬性和配置文件中相關的配置進行綁定。prefix = “person”:配置文件中哪個下面的所有屬性進行一一映射

    package com.springbootlog.springbootlog.bean;
    
    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String name;
        private int age;
        private String addr;
    
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getAddr() {
            return addr;
        }
        public void setAddr(String addr) {
            this.addr = addr;
        }
        
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", addr='" + addr + '\'' +
                    '}';
        }
    }
    
    person:
      name: zhangsan
      age: 18
      addr: China
    
    package com.springbootlog.springbootlog;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    class SpringbootLog02ApplicationTests {
        @Autowired
        Person person;
    
        @Test
        void contextLoads() {
            System.out.println(person);
        }
    }
    

    在這裏插入圖片描述

  • @PropertySource加載指定的properties屬性文件。
    使用場景我們可以在默認配置文件中配置和SpringBoot相關的屬性,在其他文件中配置程序需要的配置屬性。之後使用@PropertySource註解讀取。

    # person.properties
    person.name=lisi
    person.age=20
    person.addr=US
    
    package com.springbootlog.springbootlog.bean;
    
    @PropertySource(value = {"classpath:person.properties"})
    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
    
        private String name;
    
        private int age;
    
        private String addr;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getAddr() {
            return addr;
        }
    
        public void setAddr(String addr) {
            this.addr = addr;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", addr='" + addr + '\'' +
                    '}';
        }
    }
    

    在這裏插入圖片描述

  • @ImportResource導入Spring的配置文件,讓配置文件裏面的內容生效;
    Spring Boot裏面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;
    想讓Spring的配置文件生效,加載進來;@ImportResource標註在一個配置類上。

    package com.springbootlog.springbootlog.controller;
    
    public class HelloController {
    }
    
    <?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="helloController" class="com.springbootlog.springbootlog.controller.HelloController"></bean>
    </beans>
    
    package com.springbootlog.springbootlog;
    
    @ImportResource(locations = {"classpath:beans.xml"})
    @SpringBootApplication
    public class SpringbootLog02Application {
        public static void main(String[] args) {
            SpringApplication.run(SpringbootLog02Application.class, args);
        }
    }
    
    package com.springbootlog.springbootlog;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    class SpringbootLog02ApplicationTests {
    
        @Autowired
        Person person;
    
        @Autowired
        ApplicationContext applicationContext;
    
        @Test
        void contextLoads() {
            boolean helloController = applicationContext.containsBean("helloController");
            System.out.println(helloController);
        }
    }
    

    在這裏插入圖片描述
    我們新創建了一個HelloController,使用最原始的beans.xml這種方式去註冊bean,如果我們不使用@ImportResource註解,SpringBoot程序不會把HelloController註冊到IOC容器中,當使用@ImportResource註解後,我們自定義的bean也會被加入到IOC容器,在測試類中我們看到再IOC容器中包含了再beans.xml中配置的bean。

    SpringBoot推薦使用全註解的方式
    1、配置類@Configuration(替代之前的Spring配置文件)
    2、使用@Bean給容器中添加組件。

    /**
     * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
     *
     * 在配置文件中用<bean><bean/>標籤添加組件
     */
    @Configuration
    public class MyApplicationConfig{
        //將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
        @Bean
        public HelloController helloController(){
            return new HelloService();
        }
    }
    
Profile

Profile是SpringBoot對不同環境提供不同配置功能的支持,可以通過激活、指定參數等方式快速切換環境。

  • 多Profile支持
    我們在主配置文件編寫的時候,文件名可以是 application-{profile}.properties/yml。默認使用application.properties的配置。
    例如 application-dev.yml,application-uat.yml,application-prod.yml。

  • yml支持多文檔塊方式
    可以使用三個-在yml中作爲分割符,可以分割成多個文檔。

    server:
      port: 8081
    spring:
      profiles:
        active: prod
    ---
    server:
      port: 8083
    spring:
      profiles: dev
    ---
    server:
      port: 8084
    spring:
      profiles: uat
    ---
    server:
      port: 8084
    spring:
      profiles: prod  
    
  • 激活指定profile

    • 在application.properties中指定要激活哪一個配置文件。
      spring.profiles.active=dev
      
    • 在application.yml中指定要激活哪一個配置文件。
      spring:
        profiles:
          active: prod
      
    • 命令行 --spring.profiles.active=dev
      java -jar springboot-log-02.jar --spring.profiles.active=dev
      
    • 虛擬機參數 -Dspring.profiles.active=dev,使用IDEA啓動的時候配置JVM參數。
      在這裏插入圖片描述

加載順序

SpringBoot啓動會掃描以下位置的application.properties或者application.yml文件作爲SpringBoot的默認配置文件。

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/
    在這裏插入圖片描述

優先級由高到底,高優先級的配置會覆蓋低優先級的配置;SpringBoot會從這四個位置全部加載主配置文件;互補配置

我們還可以通過spring.config.location來改變默認的配置文件位置

項目打包好以後,我們可以使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;指定配置文件和默認加載的這些配置文件共同起作用形成互補配置;

java -jar springboot-log-02.jar --spring.config.location=/opt/app/application.properties

自動配置原理。

配置文件能配置的屬性參照:
https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/#common-application-properties

  • SpringBoot啓動的時候加載主配置類,開啓了自動配置功能 @EnableAutoConfiguration

    @SpringBootConfiguration
    @EnableAutoConfiguration
    public @interface SpringBootApplication {
    
  • @EnableAutoConfiguration 作用:

    • EnableAutoConfiguration導入了一個AutoConfigurationImportSelector.class組件。該組件是我們要導入哪些組件的選擇器。它會將所有需要導入的組件以全類名的方式存到一個AutoConfigurationImportSelector.AutoConfigurationEntry類型的內部類中返回。之後這些組件就會被添加到spring容器中。
      @Import({AutoConfigurationImportSelector.class})
      public @interface EnableAutoConfiguration {
      
      public class AutoConfigurationImportSelector {
          public String[] selectImports(AnnotationMetadata annotationMetadata) {
              if (!this.isEnabled(annotationMetadata)) {
                  return NO_IMPORTS;
              } else {
                  AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
                  AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
                  return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
              }
      	}
      }
      
    • AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);獲取候選的配置
      掃描所有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.CloudServiceConnectorsAutoConfiguration,\
      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.CassandraReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
      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.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveRestClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
      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.RedisReactiveAutoConfiguration,\
      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.elasticsearch.rest.RestClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
      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.http.HttpMessageConvertersAutoConfiguration,\
      org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
      org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
      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.groovy.template.GroovyTemplateAutoConfiguration,\
      org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
      org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
      org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
      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.mongo.embedded.EmbeddedMongoAutoConfiguration,\
      org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
      org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
      org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
      org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
      org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
      org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
      org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
      org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
      org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
      org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
      org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
      org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
      org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
      org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
      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.client.RestTemplateAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
      org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
      org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
      
      每一個這樣的 xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中;用他們來做自動配置;
  • 以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類中獲取的,這些類裏面的每一個屬性又是和配置文件綁定的;

  • 所有在配置文件中能配置的屬性都是在xxxxProperties類中封裝者‘;配置文件能配置什麼就可以參照某個功能對應的這個屬性類

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

總結

總之,SpringBoot自動配置的精髓就是:

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

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

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

​ 4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值;

xxxxAutoConfigurartion:自動配置類;給容器中添加組件

xxxxProperties:封裝配置文件中相關屬性;

如果本篇博客有任何錯誤,請批評指教,不勝感激 !
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章