spring boot載入自定義配置源
概述
我們知道,在Spring boot中可以通過xml或者@ImportResource來引入自己的配置檔案,但是這裡有個限制,必須是本地,而且格式只能是 properties(或者 yaml)。那麼,如果我們有遠端配置,如何把他引入進來來呢。
第一種方式
這外一種方法,相對更簡單些,但是相對沒那麼“優雅”。就是通過EnvironmentPostProcessor介面把我們自定義的propertySource加入environment中,
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { //這裡可以自定義一個MyPropertySource,來儲存配置資訊 MyPropertySource propertySource = new MyPropertySource("myPropertySource"); environment.getPropertySources().addLast(propertySource); } }
同時需要在META-INFO/spring.factories中加入
org.springframework.boot.env.EnvironmentPostProcessor=com.lizo.MyEnvironmentPostProcessor
第二種方式
第二種方式可能相對比較複雜一點,其實是參考Sprng cloud中的做法,其實也只需要3步
第一步,編寫PropertySource
編寫一個類繼承EnumerablePropertySource,然後實現它的抽象方法即可,抽象方法看名字就知道作用,簡單起見,這裡使用一個map來儲存配置,例如:
public class MyPropertySource extends EnumerablePropertySource<Map<String,String>> { public MyPropertySource(String name, Map source) { super(name, source); } //獲取所有的配置名字 @Override public String[] getPropertyNames() { return source.keySet().toArray(new String[source.size()]); } //根據配置返回對應的屬性 @Override public Object getProperty(String name) { return source.get(name); } }
第二步,編寫PropertySourceLocator
PropertySourceLocator 其實就是用來定位我們前面的PropertySource,需要重寫的方法只有一個,就是返回一個PropertySource物件,例如,
public class MyPropertySourceLocator implements PropertySourceLocator { @Override public PropertySource<?> locate(Environment environment) { //簡單起見,這裡直接建立一個map,你可以在這裡寫從哪裡獲取配置資訊。無論是本地還是遠端 Map<String,String> properties = new HashMap<>(); properties.put("myName","lizo"); MyPropertySource myPropertySource = new MyPropertySource("myPropertySource",properties); return myPropertySource; } }
第三步,讓PropertySourceLocator生效
新建一個配置類,例如
@Configuration
public class MyConfigBootstrapConfiguration {
@Bean
public MyPropertySourceLocator myPropertySourceLocator(){
return new MyPropertySourceLocator();
}
}
最後再建立/更新 META-INFO/spring.factories
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.lizo.MyConfigBootstrapConfiguration
簡單來說就是給Spring Boot說,這個是一個啟動配置類(看名字一種優先順序很高的配置類)。
編寫測試
測試一
@SpringBootApplication
public class Test2 {
public static void main(String[] args) throws SQLException {
ConfigurableApplicationContext run = SpringApplication.run(Test2.class, args);
Ser bean = run.getBean(Ser.class);
System.out.println(bean.getMyName());
}
@Component
public static class Ser{
@Value("${myName}")
private String myName;
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
}
}
測試二
我們在application配置檔案中,引入這個變數呢,例如在application.properties中
my.name=${myName}
同樣,結果也是能夠生效的
myName就是上面在PropertySourceLocator中寫進去的配置屬性。執行程式,可以看見確實是可以正確輸出。
小結
上面只是拋磚引玉,這樣無論是哪裡的資料來源,都可以通過這種方式編寫,把配置交給Spring 管理。這樣再也不怕在本地配置檔案中出現敏感資訊啦,再也不怕修改配置檔案需要登入每一個機器修改啦。