天天看點

補習系列(10)-springboot 之配置讀取

簡介

在早前的部落格中曾經寫過 Spring 程式通過 Bean 映射實作配置資訊的讀取。

在SpringBoot 架構中讀取配置的方式變得非常多樣,這導緻讀者在搜尋資料時反而容易迷糊。

  • 到底,SpringBoot 是按什麼順序加載配置?
  • 相應的,我們該選擇什麼樣的方式去讀取?

一、配置樣例

先看一個例子:

@Compoment
public class BuildConfig{

   @Value("${buildinfo.version")
   private String version;

  ...
}           

代碼中,@Component 将 BuildConfig 注冊為 Bean ,

接下來使用 @Value 注解,将 配置中的 buildinfo.version鍵映射到了 version 字段上。

我們都知道,通過 application.properties 可以友善的配置一些屬性。

屬性的值是支援變量替換的,如下:

myName=Lilei
myDesc=${myName} is a good man            

這點,是由 SpringBoot 自動生成的 PropertyPlaceholderConfigurer 對象實作的。

除了 上面所說 application.properties 之外,還有什麼途徑?

下面介紹如何注入配置

二、如何注入配置

1. 預設配置檔案

類路徑中 application.properties(yml) 是預設的配置檔案。

此外如果啟動應用時,目前目錄中存在同名的配置檔案,則以此優先。

在此規則之下,SpringBoot 還能識别不同 profile下的配置,這将在後面篇幅中介紹。

2. 使用注解

@PropertySource

可指定屬性配置檔案的位置,

樣例代碼:

@Configuration

@PropertySource("classpath:/com/myco/app.properties")

public class AppConfig {

     @Autowired

     Environment env;



     @Bean

     public TestBean testBean() {

         TestBean testBean = new TestBean();

         testBean.setName(env.getProperty("testbean.name"));

         return testBean;

     }

}           

@TestPropertySource

與 @PropertySource 類似,該注解用于指定測試環境中的屬性檔案,其優先級高于 @PropertySource。

3. 啟動參數

以下的指令以指定參數啟動 SpringBoot 應用

java -jar application.jar --server.port=9000           

server.port 值将被注入為環境屬性值。

而以下的指令還可以指定 配置檔案的位置

java -jar application.jar --spring.config.location=/etc/xxx.properties           

這個spring.config.location就是指的配置檔案位置,

預設情況下,SpringBoot 會從下面幾路徑找到配置檔案:

路徑
file:./config/
file:./
classpath:/config/
classpath:/

還有..

SpringBoot 注入配置的方式其實非常多,完整順序如下表:

優先級 配置
1 @TestPropertySource 注解
2 @SpringBootTest 注解
3 指令行參數
4 SPRING_APPLICATION_JSON 屬性值(或環境變量)
5 Servlet 相關參數
6 JNDI 屬性
7 Java 系統屬性 (System.getProperties())
8 作業系統環境變量
9 RandomValuePropertySource 随機屬性
10 Jar包外部 application-{profile}.properties
11 Jar包内部 application-{profile}.properties
12 Jar包外部 application.properties
13 Jar包内部 application.properties
14 @PropertySource 注解
15 SpringApplication 預設值

三、如何讀取配置

@Value 注解

如以下的實作:

@Configuration
public class AppConfig {
    
    @Value("${api.log.enabled:false}")
    private boolean apiLogEnabled;           

除了類型自動轉換之外,通過:false字尾可以指定預設值。

Environment 接口

Environment 是一個類似 Properties 的接口,用來擷取屬性非常友善。

@Configuration
public class AppConfig {

    @Autowired
    private Environment environment;

    public String getApplicationId() {
        return this.environment.getProperty("application.id");
    }
}           

@ConfigurationProperties 注解

該注解一般用作字首比對,下面的代碼摘自Mongodb

@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoProperties {

 /**
  * Mongo server host.
  */
 private String host;

 /**
  * Mongo server port.
  */
 private Integer port = null;

 /**
  * Database name.
  */
 private String database;
           

相應的 Mongodb 配置資訊如:

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=xxx
           

四、不同環境中的配置

Spring 提供了 Profile 機制用于管理不同環境的配置。

配置内容可以是 Java Config(對應@Component或@Configuration),也可以是配置檔案。

如:

@Configuration
@Profile("prod")
public class ProdConfiguration {

 // ...

}           

通過@Profile注解可将代碼配置關聯到某個配置環境

在具體應用中,Profile的用途通常有二:

1. 差別開發、測試、釋出環境

對于dev、prod、test分别做不同的配置

//for dev
application-dev.properties

//for prod
application-prod.properties

//for test
application-test.properties           

可以在 application.properties 指定啟用的環境:

spring.profiles.active=dev           

也可以通過指令行指定:

java -jar app.jar --spring.profiles.active=prod           

2. 聲明多配置檔案

當内容過多時,可以将配置資訊進行拆分,如下:

application-mongodb.properties

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.username=xxx
spring.data.mongodb.password=xxx
spring.data.mongodb.database=xxx           

application-mail.properties

spring.mail.host=xxx
spring.mail.username=xxx
spring.mail.password=xxx

spring.mail.from=xxx
spring.mail.to=xxx
spring.mail.cc=xxx           

在主配置檔案指定包含關系:

application.properties

spring.profiles.include=mongodb,mail           

參考文檔

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

歡迎繼續關注"美碼師的補習系列-springboot篇" ,如果覺得老司機的文章還不賴,請多多分享轉發^-^