【问题标题】:Classloader specific properties类加载器特定属性
【发布时间】:2011-04-12 19:32:24
【问题描述】:
我们开发了一个应用程序容器,它为容器中运行的每个独立应用程序创建一个新的类加载器。当调用特定应用程序时,线程的上下文类加载器会通过应用程序的类加载器进行适当设置。
避免使用 ThreadLocal,是否可以在类加载器中存储属性,这样您就可以直接从类加载器中检索特定于应用程序的属性。
例如,我希望能够在访问上下文类加载器时以某种方式保存然后检索属性:
Thread.currentThread().getContextClassLoader()
这可能吗?还是 ThreadLocal 是唯一可行的选择?
【问题讨论】:
标签:
java
classloader
thread-local
contextclassloader
【解决方案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
不需要线程本地或强制转换当前的类加载器。
【解决方案2】:
如何子类化上下文类加载器,使用所需的属性支持对其进行扩展,然后只转换 Thread.currentThread().getContextClassLoader()?