2011-04-12 32 views
0

我們開發了一個應用程序容器,爲容器中運行的每個獨立應用程序創建一個新的類加載器。當一個特定的應用程序被調用時,線程的上下文類加載器可以通過應用程序的類加載器進行適當的設置。類加載器的具體屬性

避免使用ThreadLocal,是否有可能在類加載器中存儲屬性,以便您可以直接從類加載器中檢索特定於應用程序的屬性。

例如,我希望能夠以某種方式保存,然後訪問上下文類加載器時以後檢索屬性:

Thread.currentThread().getContextClassLoader() 

這可能嗎?或者是ThreadLocal唯一可行的選擇?

回答

0

如何對上下文classloader進行子類化,然後使用您需要的屬性支持進行擴展,然後只需轉換Thread.currentThread()。getContextClassLoader()?

1

而不是投射類加載器,您可以讓它加載自定義屬性類,例如,

public class AppClassloaderProperties 
{ 
    static Properties appProperties = loadAppProperties(); 

    static private Properties loadAppProperties() { 
     // fetch app properties - does not need to be thread-safe, since each invocation 
     // of this method will be on a different .class instance 
    } 

    static public final Properties getApplicationProperties() { 
     // this method should be thread-safe, returning the immutable properties is simplest 
     return new Properties(appProperteis); 
    } 
} 

由於該類作爲應用程序的類加載器的一部分加載,因此會爲每個應用程序提供一個新類。每個應用程序的AppClassloaderProperties類將有所不同。然後,每個應用程序可以通過調用

Properties props = AppClassloaderProperties.getApplicationProperties(); 
// use the properties 

無需線程局部變量或鑄造當前的類加載器獲取其類加載器的屬性。