2013-02-02 92 views

回答

2

如果你打算親自去做,我建議你創建一個配置類,它通過構造函數接受文件,並將屬性值讀入成員變量。然後每個需要配置的類都通過它的構造函數接受一個Configuration類。但是,幾乎沒有人這樣做,而是使用像Spring這樣的框架,它爲您處理屬性注入。

在春天,它會是這個樣子:

<!-- application context xml file --> 
<context:property-placeholder location="file:///some/path/to/file" /> 
在Java類中

然後:

public class SomeClass { 
    @Value("${some.property}") 
    private String someProp; 

    @Value("${some.other.prop}") 
    private Integer someOtherProp; 

    // ... 
} 

啓動應用程序時性能得到注入類。

0

我的建議是有一個Util類加載屬性文件並從該Util獲取值到所需的類。

注意:我不認爲你有任何加載屬性文件的問題。

0

我建議你創建一個不可變的類,它接受文件作爲構造函數參數並設置所有的實例變量。我會稱之爲PropertyConfiguration。然後,因爲課程是不可改變的,所以您不必擔心將其傳遞給每個人。你甚至可以擁有一個擁有它的課程。

例如,下面的代碼會讓你有一個很好的設置,以便在項目範圍內有幾件事情可用。我只是要確保共享的任何東西都是不可變的,以確保線程安全。

public class ClientUtils { 

    private static ClientContext _clientContext = null; 

    public static void setClientContext(ClientContext cc) { 
     _clientContext = cc; 
    } 

    public static ClientContext getContext() { 
     return _clientContext; 
    } 
} 

public class ClientContext { 

    private final Configuration _configuration; 

    public ClientContext(Configuration config){ 
     _configuration = config; 
    } 

    public Configuration getClientContext() { 
     return _configuration; 
    } 

} 
0

如果你的程序中包含它不必是編譯的一部分,可以從部署到部署的變化數據,你必須把它加到屬性文件:(比如像數據庫連接字符串,電子郵件地址)。

爲了防止您需要此操作,我添加了訪問屬性文件的代碼。 刪除文件build目錄。

Properties properties = new Properties();  
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("credentials.properties"));