本文參考《Spring Boot實戰》第4版第3.2章節通過屬性文件外置配置。
Spring Boot提供了一系列的默認配置,如果想自定義配置怎麼辦,這裏給出了3種辦法。
自動配置微調
常用的方法就是在application.yml中進行配置,覆蓋默認的配置。
應用程序Bean的配置外置
在開發應用程序時,往往有很多可配置的參數,不能寫死在程序裏,因此需要配置文件來配置。這時可以通過提供一些配置類來讀取配置文件中的參數,然後提供給應用程序使用。
使用Profile進行配置
當應用程序需要部署到不同的環境時,一些配置細節通常會有不同,比如開發環境、測試環境和生成環境等。Spring Boot支持基於Profile的配置。Profile是一種條件化配置,基於運行時激活的Profile,會使用或者忽略不同的Bean或配置類。
實例
本實例基於Parker項目進行擴展,源代碼見 https://github.com/wu-boy/parker.git
新建parker-config模塊,配置文件如下
application.yml
spring:
profiles:
active: dev
application-dev.yml
global-config:
name: dev
application-prod.yml
global-config:
name: prod
如果使用YAML來配置屬性,可創建application-{profile}.yml這樣的文件,並將與Profile無關的屬性繼續放在application.yml裏。
新建配置類
package com.wu.parker.config.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author: wusq
* @date: 2019/1/10
*/
@Component
@ConfigurationProperties("global-config")
public class GlobalConfig {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
該配置類用於讀取global-config中的name配置的值,加上@ConfigurationProperties註解,就可以收集配置屬性了。
Spring Boot的屬性解析器非常智能,它會自動把駝峯規則的屬性和使用連字符“-”或下劃線“_”的同名屬性關聯起來。
啓動類
package com.wu.parker.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author: wusq
* @date: 2019/1/10
*/
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
測試類
package com.wu.parker.config.test;
import com.wu.parker.config.config.GlobalConfig;
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;
/**
* @author: wusq
* @date: 2019/1/10
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GlobalConfigTest {
@Autowired
private GlobalConfig globalConfig;
@Test
public void contextLoads() {
}
@Test
public void test() throws Exception {
System.out.println(globalConfig.getName());
}
}
修改application.yml中的active屬性,可以加載不同的配置文件。