概述
我們知道,在Spring boot中可以通過xml或者@ImportResource 來引入自己的配置文件,但是這里有個限制,必須是本地,而且格式只能是 properties(或者 yaml)。那么,如果我們有遠程配置,如何把他引入進來來呢。
如何做
其實自定義配置源只需要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生效
新建一個配置類,例如
@Configurationpublic class MyConfigBootstrapConfiguration { @Bean public MyPropertySourceLocator myPropertySourceLocator(){ return new MyPropertySourceLocator(); }}
最后再創建/更新 META-INFO/spring.factories(如果做過自定義Spring boot開發的都知道這個文件)
org.springframework.cloud.bootstrap.BootstrapConfiguration=/com.lizo.MyConfigBootstrapConfiguration
簡單來說就是給Spring Boot說,這個是一個啟動配置類(一種優先級很高的配置類)。
編寫測試
測試一
@SpringBootApplicationpublic 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 管理。這樣再也不怕在本地配置文件中出現敏感信息啦,再也不怕修改配置文件需要登錄每一個機器修改啦。
新聞熱點
疑難解答
圖片精選