ClassLoader 与 配置文件
现在,无论是企业应用还是小型项目,为了产品的灵活性、扩展性,
配置文件越来越多,以我自己尝试的一个web应用来说,在xml配置文件中,
添加自己的配置参数或初始化参数时遇到的关于“参数的路径与处理这个参数的类的classloader有关”,
比如,在我前面做的(小框架中),
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/classes/properties/init.properties</value>
</property>
</bean>
配置了Spring初始化需要的参数,有的开源项目处理时是自己写的类处理的,或者利用Spring处理,
(spring的类是/WEB-INF/classes/org/springframework/....)
所以参数如果需要路径一般写为"/properties/*.* ",而如果你利用容器的一些东西处理,
比如说apache中的类处理,那么你就要将参数改写为"/WEB-INF/classes/properties/*.* ",(比如我们的包结构为com.myapp),
那么我们用自己的类处理时,加载我们类的classloader是com.myapp....(指WEB-INF/classes/ 下),
如果是apache的类处理时,加载类的classloader就是加载web应用上面的(比如我的应用D:/myapp/WEB-INF/......),这样
classloader加载参数时从myapp开始,所以参数必须加上/WEB-INF/classes/.....才可以。
Resource--getInputStream()方法,
你就会发现他的classloader是什么了!!!
public InputStream getInputStream() throws IOException {
InputStream is = null;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else {
ClassLoader cl = this.classLoader;
if (cl == null) {
// no class loader specified -> use thread context class loader
cl = Thread.currentThread().getContextClassLoader();
}
is = cl.getResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(
getDescription() + " cannot be opened because it does not exist");
}
return is;
}