class.getClassLoader()返回空值null:解决办法
配置一个Spring环境,将Spring framework 和这些依赖包添加到工程中,我把它们分别做成了一个User Library,如下图

然后把它们添加到工程中,如下图

添加进去后就可以运行一个简单的程序测试
publicclassTestBatch{
private static ApplicationContext context;
@SuppressWarnings("unchecked")
publicstaticvoid main(finalString[] args){
context =newClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");
try{
@SuppressWarnings("unused")
TestBatch app =newTestBatch();
}catch(Exception ex){
ex.printStackTrace();
}
}
publicvoidTestBatch(){/** Do Something using the context **/}
}
结果就出现了如下错误:

是这里引起的:
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:106)
... 7 more
一看源代码,是这样的:
static{
ClassLoader cl =DefaultListableBeanFactory.class.getClassLoader();
try{
javaxInjectProviderClass = cl.loadClass("javax.inject.Provider");//Line 106
}
catch(ClassNotFoundException ex){
// JSR-330 API not available - Provider interface simply not supported then.
}
}
源代码的问题在于:
ClassLoader cl =DefaultListableBeanFactory.class.getClassLoader();返回空!
原来是这个DefaultListableBeanFactory通过BootStrap直接加载,getClassLoader()的时候返回null
JDK上也有说明:
"public ClassLoader getClassLoader()返回该类的类加载器。有些实现可能使用 null 来表示引导类加载器。如果该类由引导类加载器加载,则此方法在这类实现中将返回 null。 "
细细想来,原来是这里错了:勾选了System library(added to the boot class path),DefaultListableBeanFactory被当成系统Jar通过BootStrap直接加载
把这个勾去了就好了
