天天看點

spring-boot 配置檔案詳解:Properties和YAML時間格式化時區設定

一.配置檔案的生效順序,會對值進行覆寫:

1. @TestPropertySource 注解

2. 指令行參數

3. Java系統屬性(System.getProperties())

4. 作業系統環境變量

5. 隻有在random.*裡包含的屬性會産生一個RandomValuePropertySource

6. 在打包的jar外的應用程式配置檔案(application.properties,包含YAML和profile變量)

7. 在打包的jar内的應用程式配置檔案(application.properties,包含YAML和profile變量)

8. 在@Configuration類上的@PropertySource注解

9. 預設屬性(使用SpringApplication.setDefaultProperties指定)

二.配置随機值

withmes.secret=${random.value}
withmes.number=${random.int}
withmes.bignumber=${random.long}
withmes.number.less.than.ten=${random.int()}
withmes.number.in.range=${random.int[,]}
           

讀取使用注解:

@Value(value = "${withmes.secret}")

注:出現黃點提示,是要提示配置中繼資料,可以不配置

三.屬性占位符

當application.properties裡的值被使用時,它們會被存在的Environment過濾,是以你能夠引用先前定義的值(比如,系統屬性)。

withmes.name=www.withmes.com
withmes.desc=${withmes.name} is a domain name
           

四.Application屬性檔案,按優先級排序,位置高的将覆寫位置低的

1. 目前目錄下的一個/config子目錄

2. 目前目錄

3. 一個classpath下的/config包

4. classpath根路徑(root)

這個清單是按優先級排序的(清單中位置高的将覆寫位置低的)

五. 配置應用端口和其他配置的介紹

#端口配置:

時間格式化

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
           

時區設定

spring.jackson.time-zone=Asia/Chongqing
           

六. 使用YAML代替Properties

注意寫法:冒号後要加個空格

例如:第二行開頭用tab

withmes:  
  adders: 1221
           

多環境配置

例如現在項目有測試環境和生産環境,測試環境和生産環境的伺服器位址是不同的,那麼可以使用多環境配置

1,首先在 application.properties 中

意思是 激活 spring.profiles.active-test 檔案中的配置

spring.profiles.active=test
           

這樣就可以靈活的配置測試環境和生産環境不同的一些資訊,而不需要修改大量代碼

logback(日志配置)

spring boot預設會加載classpath:logback-spring.xml或者classpath:logback-spring.groovy

使用自定義配置檔案,配置方式為:
logging.config=classpath:logback-withmes.xml
注意:不要使用logback這個來命名,否則spring boot将不能完全執行個體化

1.使用基于spring boot的配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>


2.使用log4j2
![123](https://img-blog.csdn.net/20180421225644465?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxOTIwNDQ3OTM5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

去除logback的依賴包,添加log4j2的依賴包
<exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

<!-- 使用log4j2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
然後在
application.properties 配置 
logging.config=classpath:yourlog4j2name.xml
           

繼續閱讀