主頁 > 後端開發 > 2、Spring Boot配置

2、Spring Boot配置

2020-10-09 03:11:51 後端開發

1.組態檔

  SpringBoot使用一個全域的組態檔,組態檔名是固定的;

    ?application.properties

    ?application.yml

  組態檔的作用:修改SpringBoot自動配置的默認值;SpringBoot在底層都給我們自動配置好;

  YAML(YAML Ain't Markup Language):以資料為中心,比json、xml等更適合做組態檔;以前的組態檔;大多都使用的是xxxx.xml檔案;

范例:YAML配置例子

server:

  port: 8081

范例:XML配置

<server>

    <port>8081</port>

</server>

2.YAML語法

[1].基本語法

語法: K: V:表示一對鍵值對(: v之間有個空格)

  空格的縮進來控制層級關系;只要是左對齊的一列資料,都是同一個層級的

server:

    port: 8081

    path: /hello

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

[2].值的寫法

(1).普通的值(數字,字串,布爾)

?  k: v:字面直接來寫;

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

    "":雙引號;不會轉義字串里面的特殊字符;特殊字符會作為本身想表示的意思

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

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

      name: ‘zhangsan \n lisi’:輸出;zhangsan \n  lisi

(2).物件、Map(屬性和值)(鍵值對)

  k: v:在下一行來寫物件的屬性和值的關系;注意縮進

  物件還是k: v的方式

friends:

    lastName: zhangsan

    age: 20

  行內寫法:

friends: {lastName: zhangsan,age: 18}

(3).陣列(List、Set)

  - 值表示陣列中的一個元素

pets:

  - cat

  - dog

  - pig

  行內寫法

pets: [cat,dog,pig]

[3].組態檔值注入

application.yml

server:

  port: 8081

 

 

person:

  lastname: zhangsan

  age: 18

  boss: false

  birth: 2020/1/1

  maps: {k1: v1,k2: 12}

  lists:

    - lisi

    - zhaoliu

    - zhangsan

  dog:

    name: 狗狗

    age: 2

javaBean:

/**

 *  將組態檔中配置的每一個屬性的值,映射到這個組件中

 *  @ConfigurationProperties: 告訴SpringBoot將本類中的所有屬性和組態檔中相關的配置進行系結 默認從全域組態檔中獲取值

 *      prefix="person":組態檔中將下面的所有屬性進行一一映射

 */

@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>

   <version>2.1.6.RELEASE</version>

   <optional>true</optional>

</dependency>

(1).properties組態檔在idea中默認utf-8可能會亂碼

 

(2).@Value獲取值和@ConfigurationProperties獲取值比較

  組態檔yml還是properties以上方式都能獲取到值;

如何選擇以上方式:

  如果說,我們只是在某個業務邏輯中需要獲取一下組態檔中的某項值,使用@Value;

  如果說,我們專門撰寫了一個javaBean來和組態檔進行映射,我們就直接使用@ConfigurationProperties;

(3).組態檔注入值資料校驗

@Component

@ConfigurationProperties(prefix = "person")

@Validated

public class Person {

 

    /**

     * <bean >

     *      <property name="lastName" value="https://www.cnblogs.com/CSAH/archive/2020/10/08/字面量/${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;

(4).@PropertySource&@ImportResource&@Bean

@PropertySource:加載指定的組態檔;

/**

 *  將組態檔中配置的每一個屬性的值,映射到這個組件中

 *  @ConfigurationProperties: 告訴SpringBoot將本類中的所有屬性和組態檔中相關的配置進行系結 默認從全域組態檔中獲取值

 *      prefix="person":組態檔中將下面的所有屬性進行一一映射

 */

@PropertySource(value=https://www.cnblogs.com/CSAH/archive/2020/10/08/{"classpath:person.properties"})

@Component

@ConfigurationProperties(prefix = "person")

//@Validated

public class Person {

 

    /**

     *  <bean >

     *      <properties name="lastName" value="https://www.cnblogs.com/CSAH/archive/2020/10/08/字面量/${key}從環境變數、組態檔中獲取值/#{SpEL}"></properties>

     *  </bean>

     */

//    @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;

@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.pluto.springboot.service.HelloService"></bean>

 

</beans>

SpringBoot推薦給容器中添加組件的方式;推薦使用全注解的方式

1)、配置類@Configuration------>Spring組態檔

2)、使用@Bean給容器中添加組件

/**

 * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring組態檔

 *

 * 在組態檔中用<bean><bean/>標簽添加組件

 *

 */

@Configuration

public class MyAppConfig {

 

    //將方法的回傳值添加到容器中;容器中這個組件默認的id就是方法名

    @Bean

    public HelloService helloService02(){

        System.out.println("配置類@Bean給容器中添加組件了...");

        return new HelloService();

    }

}

[4].組態檔占位符

 

# idea組態檔默認為utf-8

#????Person???

person.last-name=張三${random.uuid}

person.age=${random.int}

person.birth=2020/1/1

person.boss=false

person.maps.k1=v1

person.maps.k2=14

person.lists=a,b,c

person.dog.name=${person.last-name}_dog

person.dog.age=15

[5].Profile

在主組態檔撰寫的時候,檔案名可以是   application-{profile}.properties/yml

默認使用application.properties的配置;

(1).在組態檔中指定開發環境

application.properties

server.port=8081

spring.profiles.active=dev

application-dev.properties

server.port=8083

(2).yml檔案快

  yml支持多檔案塊方式

 

server:

  port: 8081

spring:

  profiles:

    active: prod

---

 

server:

  port: 8083

spring:

  profiles: dev

---

 

server:

  port: 8088

spring:

  profiles: prod

(3).激活指定profile

1).在組態檔中指定spring.profiles.active=dev

2).命令列

(1.Program arguments

 

(2.CMD

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

 

(3.虛擬機引數

-Dspring.profiles.active=dev

 

[6].組態檔加載位置

springboot 啟動會掃描以下位置的application.properties或者application.yml檔案作為Spring boot的默認組態檔

–file:./config/

–file:./

–classpath:/config/

–classpath:/

優先級由高到底,高優先級的配置會覆寫低優先級的配置;

SpringBoot會從這四個位置全部加載主組態檔;它們成互補配置;

 

我們還可以通過spring.config.location來改變默認的組態檔位置

  專案打包好以后,我們可以使用命令列引數的形式,啟動專案的時候來指定組態檔的新位置;指定組態檔和默認加載的這些組態檔共同起作用形成互補配置;

  通過packet生成jar包

 

 

D:\DevCode\spring-boot-02-config-02\target>java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

[7].外部配置加載順序

  https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config

 

SpringBoot也可以從以下位置加載配置; 優先級從高到低;高優先級的配置覆寫低優先級的配置,所有的配置會形成互補配置

(1).命令列

  多個配置用空格分開; --配置項=值

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8086  --server.context-path=/hello

(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指定的默認屬性

所有支持的配置加載來源:參考官方檔案

[8].Spring自動配置原理

組態檔到底能寫什么?怎么寫?自動配置原理;

組態檔能夠配置的屬性參照

(1).自動配置原理

1).Spring啟動的時候會自動加載主配置類,開啟了自動配置功能@SpringBootApplication

 

2).@EnableAutoConfiguration 作用

 

利用AutoConfigurationImportSelector給容器中匯入一些組件

 

查看selectImports()方法的內容

 

獲取候選的配置

return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());

 

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.context.ConfigurationPropertiesAutoConfiguration,\

org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\

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.ElasticsearchDataAutoConfiguration,\

org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\

org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\

org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\

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.r2dbc.R2dbcDataAutoConfiguration,\

org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\

org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\

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.ElasticsearchRestClientAutoConfiguration,\

org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\

org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\

org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\

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.jersey.JerseyAutoConfiguration,\

org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\

org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\

org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\

org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\

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.r2dbc.R2dbcAutoConfiguration,\

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類都是容器中的一個組件,都加入到容器中;用他們來做自動配置;

3).每一個自動配置類進行自動配置功能

4).以HttpEncodingAutoConfiguration(Http編碼自動配置)為例解釋自動配置原理

@Configuration   //表示這是一個配置類,以前撰寫的組態檔一樣,也可以給容器中添加組件

@EnableConfigurationProperties(HttpEncodingProperties.class)  //啟動指定類的ConfigurationProperties功能;將組態檔中對應的值和HttpEncodingProperties系結起來;并把HttpEncodingProperties加入到ioc容器中

 

@ConditionalOnWebApplication //Spring底層@Conditional注解(Spring注解版),根據不同的條件,如果滿足指定的條件,整個配置類里面的配置就會生效;    判斷當前應用是否是web應用,如果是,當前配置類生效

 

@ConditionalOnClass(CharacterEncodingFilter.class)  //判斷當前專案有沒有這個類CharacterEncodingFilterSpringMVC中進行亂碼解決的過濾器;

 

@ConditionalOnProperty(prefix = "spring.http.encoding", value = "https://www.cnblogs.com/CSAH/archive/2020/10/08/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");

springboot精髓:

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

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

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

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

xxxxAutoConfigurartion:自動配置類;

給容器中添加組件

xxxxProperties:封裝組態檔中相關屬性;

(2).細節

1).@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屬性;來讓控制臺列印自動配置報告,這樣我們就可以很方便的知道哪些自動配置類生效;

============================

CONDITIONS EVALUATION REPORT

============================

 

 

Positive matches: 啟用的自動配置類

-----------------

 

   AopAutoConfiguration matched:

      - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)

 

   AopAutoConfiguration.ClassProxyingConfiguration matched:

      - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)

      - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

 

 

Negative matches:

沒啟用的自動配置類

-----------------

 

   ActiveMQAutoConfiguration:

      Did not match:

         - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)

參考檔案:https://bitbucket.org/asomov/snakeyaml/wiki/Documentation#markdown-header-yaml-syntax

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/163895.html

標籤:其他

上一篇:SQLAlchemy使用

下一篇:SQLAlchemy使用

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more