3 回答
TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是一個(gè)老問(wèn)題,但是公認(rèn)的答案有一個(gè)嚴(yán)重的缺陷。如果Spring Environment對(duì)象包含任何替代值(如Externalized Configuration中所述),則不能保證它產(chǎn)生的屬性值映射將與Environment對(duì)象返回的屬性值匹配。我發(fā)現(xiàn),簡(jiǎn)單地通過(guò)迭代PropertySource的S- Environment沒(méi)有,其實(shí)給任何覆蓋值。相反,它產(chǎn)生了原始值,該值應(yīng)該被覆蓋。
這是一個(gè)更好的解決方案。本品采用EnumerablePropertySource的S- Environment迭代通過(guò)已知的屬性名稱,但隨后讀取實(shí)際值了真正的春天的環(huán)境。這樣可以保證該值是Spring實(shí)際解析的值,包括所有覆蓋的值。
Properties props = new Properties();
MutablePropertySources propSrcs = ((AbstractEnvironment) springEnv).getPropertySources();
StreamSupport.stream(propSrcs.spliterator(), false)
.filter(ps -> ps instanceof EnumerablePropertySource)
.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
.flatMap(Arrays::<String>stream)
.forEach(propName -> props.setProperty(propName, springEnv.getProperty(propName)));
- 3 回答
- 0 關(guān)注
- 1025 瀏覽
添加回答
舉報(bào)
