2016-06-17 55 views
0

我有一個名爲xyz.properties的屬性文件。現在,我可以在我的課程中加載此文件的單個屬性,並註釋爲@Component,這很好。在春天獲取屬性對象

但是,我正在考慮讓我的項目更加模塊化,爲此我需要將整個xyz.properties文件作爲一個properties對象讀取,以便我可以傳遞它。我該怎麼做?

更新

現在,我從文件中加載個人財產這樣

的applicationContext.xml具有以下條目

<context:property-placeholder location="classpath:xyz.properties" order="2" ignore-unresolvable="true"/> 

,然後我有各自的類如

@Component 
public class XyzConfiguration { 
    @Value("${client.id}") 
    private String clientId; 

    @Value("${client.secret}") 
    private String clientSecret; 

    ... 
} 

我的意思它傳遞

現在,每一個人財產我有一個類來創建相應的字段,然後用相應的屬性名稱標註它。通過這樣做,我正在使我的嵌套模塊非常具有框架特有的spring。我可能有一天會把這個模塊放在github上,他們可能會也可能不會使用spring框架。對於他們來說,通過傳遞所需的參數(理想情況下爲Properties對象)來創建此模塊的對象會更容易,以便我的模塊自己獲取屬性。

+0

你現在如何加載你的屬性文件?另外,你是什麼意思傳遞? – aksappy

回答

1

您可以嘗試下面的代碼。

import org.springframework.core.io.support.PropertiesLoaderUtils; 
import org.springframework.core.io.ResourceLoader; 
import java.util.Properties; 

private String fileLocator; 
private Properties prop; 
private ResourceLoader resourceLoader; 

public void init() throws IOException { 
     //"fileLocator" must be set as a path of file. 
     final Resource resource = resourceLoader.getResource(fileLocator); 

     prop = PropertiesLoaderUtils.loadProperties(resource); 
    } 

prop將擁有屬性文件中的所有值,然後可以通過調用prop.getProperty()方法來獲取任何值。