2015-01-26 82 views
3

在我的Java類中,我有一個類型的字段,比如java.util.Properties或java.util.Map。 我希望Spring爲所有以給定前綴開頭的屬性注入字段。理想情況下,通過在屬性註釋中指定通配符,像@Value(${prefix.*})那樣好像不起作用。Spring 3+。通過前綴在佔位符中解析屬性

我該如何做到這一點?

+0

您是否試圖在Spring Boot中閱讀這些屬性?如果是的話,你可以使用@ConfigurationProperties(prefix =「yourPrefix」)' – Mithun 2015-01-27 06:46:24

回答

1

AFAIK沒有直接的方法來實現你正在尋找的東西。

但是,您可以使用Spring EL結合自定義實現org.springframework.core.io.support.PropertiesLoaderSupport

首先延長PropertiesLoaderSupport或任何的它的子類)。介紹一個方法(說filterProps),這將返回java.util.Properties對象,具有過濾性能,如下面

public class CustomPropertyLoader extends PropertiesLoaderSupport { 

public Properties filterProperties(String prefix){ 
    Properties temp = new Properties(); 

    for(Properties props : this.localProperties){ 
     /* 
     * Iterate over props and filter them as 
     * per prefix (or any custom logic) to temp 
     */ 
    } 
    return temp; 
} 

}

提示 - 您可以使用正則表達式的更通用的方案,而不是String作爲方法參數。

定義上面的類

<bean id="customPropertyLoader" class="x.y.z.CustomPropertyLoader"> 
    <property name="locations" value="classpath*:/**/some*.properties"/> 
</bean> 

最後註釋java.util.Properties類型的類領域的相應bean作爲 @Value(#{customPropertyLoader.filterProperties('prefix.*')})

附::請原諒編譯/語法錯誤,因爲我沒有編譯並檢查設置;但它應該工作。如果不是,請在評論中告知。