SpringBoot學習日記2 配置標籤學習

SpringBoot學習日記

配置文件

默認配置文件名:java

  • application.properties
  • application.yml

一、YAML

properties:web

server.port : 8080

ymlspring

server:
    port:8080
基本語法:
  • K: V 表示鍵值對(冒號後面有空格)
  • 空格來控制層級關係,左對齊爲同一層級
  • 大小寫敏感
值的寫法:
  • 字面量 普通的值(數字、字符串、布爾)k: V

    字符串默認不用加引號,並且單引號和雙引號不同。雙引號裏面的特殊符號會被轉義。數組

  • 對象,map(屬性和值)app

    K-V寫法運維

    Friend:
    lastName: zhansan
    age: 20

    行內寫法:dom

    Friend: {lastName: zhansan,age: 18}
  • 數組ide

    寫法1 - xxxspring-boot

    Pets:
        - cat
        - dog
##### 實踐:

###### YML配置

People.class

// 必須爲容器中的組件
@Component
// 配置文件哪一個下面的全部屬性 進行映射
@ConfigurationProperties(prefix = "people")
public class People {單元測試

private String name;
private Boolean gender;
private Integer age;
private Map<String,String> books;
private List<String> lists;
private Dog dog;

}

Dog.class

@Component
public class Dog {

private String name;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Override
public String toString() {
    return "Dog{" +
            "name='" + name + '\'' +
            '}';
}

}

application.yml

people:
name: 'afsun'
gender: true
age: 24
books:

k1: v1
k2: v2

dog:

name: 小黑

lists:

- a1
- a2
- a3
- a4
- b1
pom.xml

<dependency>

<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-configuration-processor</artifactId>
<optional> true </optional>

</dependency>

配置文件處理器:幫咱們生成配置文件元數據,在配置文件件中能夠生成提示    

測試

package com.example.demo;

import com.example.demo.bean.People;
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) // 指定使用Spring的單元測試而不是Junit
@SpringBootTest
public class DemoApplicationTests {

@Autowired
People p1 ;

@Test
public void contextLoads() {
    System.out.println(p1);
}

}

###### properties方式

配置People

people.age=17
people.gender=true
people.name=afsun
people.books.key1 = v1
people.books..key2 = v2
people.lists=a,b,c
people.dog.name = 花花

輸出:

People{name='afsun', gender=true, age=17, books={key1=v1, key2=v2}, lists=[a, b, c], dog=Dog{name='����'}}

###### @Value的使用

<bean class = "People" >

<!--${key}從環境變量、配置文件中獲取、#{spEL} EL表達式-->
<property name="xxx" value="字面量/${key}/#{spel}" ></property>

</bean >

使用:

@Component
//@ConfigurationProperties(prefix = "people")
public class People {

@Value("#{11*22}")
private String name;
@Value("${people.gender}")
private Boolean gender;
private Integer age;
private Map<String,String> books;
private List<String> lists;
private Dog dog;

}

輸入:

People{name='242', gender=true, age=null, books=null, lists=null, dog=null}

#### 二、@Value和@ConfigurationProperties區別

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

若是隻是獲取配置文件中的某個值那麼久用@Value

若是專門寫一個JavaBean的配置文件則用@ConfigurationProperties

JSR303數據校驗

@Component
@Validated
@ConfigurationProperties(prefix = "people")
public class People {

@Email
private String name;
private Boolean gender;
private Integer age;
private Map<String,String> books;
private List<String> lists;
private Dog dog;

}

people.age=17
people.gender=true
people.name=afsun
people.books.key1 = v1
people.books..key2 = v2
people.lists=a,b,c
people.dog.name = gougou

輸出

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'people' to com.example.demo.bean.People failed:

Property: people.name
Value: afsun
Origin: class path resource [application.properties]:4:13
Reason: 不是一個合法的電子郵件地址
修改:

����People

people.age=17
people.gender=true
people.name= ashuash12123@qq.com
people.books.key1 = v1
people.books..key2 = v2
people.lists=a,b,c
people.dog.name = gougou

輸出正常

People{name='ashuash12123@qq.com', gender=true, age=17, books={key1=v1, key2=v2}, lists=[a, b, c], dog=Dog{name='gougou'}}

鬆散綁定:people.lastName = people.last-name*

#### 三、@PropertySource

告訴SpringBoot加載哪一個配置文件。

@PropertySource(value={"classpath:people.properties"})
@component
@configurationProperties(prefix = "")
public class people {
.....
}

@ImportRsource

導入Spring的配置文件,讓配置文件生效

SpringBoot沒有Spring的配置文件,咱們寫的配置文件不能自動是被,若是須要Spring配置文件生效則須要用此註解標註在類上(主配置類)。

@ImportResource(locations = {""})、
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

}

SpringBoot推薦使用全註解的方式,使用配置來完成

// 註明爲配置類
@configuration
public class MyConfig{

// 返回值添加到容器中,方法名爲id名
@Bean
public BeanFactory getBeanFactory(){
    /*
    
    */
}

}

#### 四、@ 配置文件佔位符

##### 一、隨機數

${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024.6454]}

##### 二、佔位符

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

People

people.age=17
people.gender=true

隨機數

people.name= ${radom.uuid}
people.books.key1 = v1
people.books..key2 = v2
people.lists=a,b,c

指示一個默認值

people.dog.name = ${people.name:afsun}_dog

#### 五、Profile

爲了切換各類環境,生產環境、開發環境、測試環境

咱們在主配置文件編寫的時候,文件名能夠是 application-{profile}.properties/yml

默認使用的是==application.properties==

##### 多文檔

多文檔:application-dev.properties、application-prod.properties....

application.properties

spring.profiles.active = dev

##### yml文檔塊

application.yml

server:

port:8083

spring:

profiles
    active:dev --指定版本

------下面是文檔塊
---開發環境
server:

port:8083

spring:

profiles:dev

---生產環境
server:

port:8084

spring:

profiles:prod

---測試環境
server:

port:8085

spring:

profiles:test
##### 命令行方式選定

program arguments:--spring.profiles.active=xxx

JVM -Dspring.profiles.active = xxx

#### 六、配置文件加載位置

- -file:./config/
- -file:./
- -classpath:/config/
- -classpath:/

優先級從高到低的順序,高優先級覆蓋低優先級內容,SpringBoot4個位置的文件所有讀取,**互補配置**

==spring.config.location== 指定默認的配置文件路徑,運維時使用。

#### 七、外部配置加載順序

能夠從如下位置加載配置,符合上面的**互補配置**

- 命令行參數 `--server.port=xxx` 多個配置用空格分開
- jar包外部的application-{profile}.properties或application.yml(帶spring.profile)(jar包外目錄)
- jar包內部的application-{profile}.properties或application.yml(帶spring.profile)
- jar包外部的application.properties或application.yml
- jar包內部的application.properties或application.yml
- @Configuration註解類上的@PropertySource
- 經過SpringApplication.setDefaultProperties指定

#### 八、自動配置原理

1. SpringBoot啓動的時候加載主配置類,開啓配置功能==@EnableAutoConfiguration==

2. @EnableAutoConfiguration

   - 獲取`META-INF/spring.factories` 中key爲EnableAutoConfiguration.class的類名加入到容器中

   - ```properties
     # Auto Configuration Import Listeners
     org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
     org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
     
     # Auto Configuration Import Filters
     org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
     org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
     org.springframework.boot.autoconfigure.condition.OnClassCondition,\
     org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition
     
     # 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,\
  • 自動配置類進行自動配置功能
  • @Configuration //爲配置類
      @EnableConfigurationProperties({HttpProperties.class}) //啓用onfigurationProperties功能,指定類的,從配置文件中獲取指定的數據,並把HttpProperties加入到容器中
      @ConditionalOnWebApplication // Spring底層@Condition註解,判斷當前應用是不是web應用
          type = Type.SERVLET
      )
      @ConditionalOnClass({CharacterEncodingFilter.class})// 判斷當前項目是否有這個類
      @ConditionalOnProperty( // 判斷配置文件中是否存在某個配置:prefix。。。
          prefix = "spring.http.encoding",
          value = {"enabled"},
          matchIfMissing = true // 不存在,也是正確的
      )
      public class HttpEncodingAutoConfiguration {
          
          /**
          *經過有參構造器得到HttpProperties而HttpProperties映射了配置文件
          */
         public HttpEncodingAutoConfiguration(HttpProperties properties) {
              this.properties = properties.getEncoding();
          }
          @Bean
          @ConditionalOnMissingBean //當beanFactory沒有該bean時
          public CharacterEncodingFilter characterEncodingFilter() {
              CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
              filter.setEncoding(this.properties.getCharset().name());
                      filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
              filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
              return filter;
          }
      }
  • HttpProperties.class

    全部在配置文件中能配置的屬性都是在xxxProperties類中封裝,配置文件能配置什麼就能夠參照某個功能對應的這個屬性類。

    @ConfigurationProperties(
        prefix = "spring.http"
    ) //根據"spring.http"能夠在配置文件中,指定屬性
    public class HttpProperties {

    根據當前的不一樣條件判斷,決定這個配置類是否生效

xxxxAutoConfiguration:自動配置類

給容器添加相應的組件

xxxproperties類做爲配置文件的映射類

自動配置實現

相關文章
相關標籤/搜索