Caused by: java.lang.NullPointerException at org.springframework.beans.factory.support.DefaultLis

刚学Spring,配置上就花了不少时间.

首先给Eclipse EE 装了一个Spring IDE

然后下载了Spring framework 3.0.6 http://www.springframework.org/

发现有很多依赖包,又在CSDN上找到了这个,是Spring 3.0.5的所有依赖:http://download.csdn.net/detail/lzgame/3548052, 一共有8个包

好了,现在需要将Spring framework 和这些依赖包添加到工程中,我把它们分别做成了一个User Library,如下图

注意上图中不要勾选System library(added to the boot class path)这一项.否则运行时会报错.稍后再讲.

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

添加进去后就可以运行一个简单的程序了(下面是主程序)

 

[html]  view plain copy
  1. publicclassTestBatch{  
  2.     private static ApplicationContext context;  
  3.     @SuppressWarnings("unchecked")  
  4.     publicstaticvoid main(finalString[] args){  
  5.             context =newClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");  
  6.             try{  
  7.                 @SuppressWarnings("unused")  
  8.                 TestBatch app =newTestBatch();  
  9.             }catch(Exception ex){  
  10.                 ex.printStackTrace();  
  11.             }  
  12.     }  
  13.     publicvoidTestBatch(){/** Do Something using the context **/}  
  14. }  

输出:Hello! How are you?

但是, 这个过程遇到了一些麻烦. 我在做User Library(第一张图)的时候,勾选了System library(added to the boot class path),结果就出现了如下错误:

 

 

是这里引起的:

Caused by: java.lang.NullPointerException
   at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:106)
   ... 7 more

一看源代码,是这样的:

[html]  view plain copy
  1. static{  
  2.     ClassLoader cl =DefaultListableBeanFactory.class.getClassLoader();  
  3.     try{  
  4.         javaxInjectProviderClass = cl.loadClass("javax.inject.Provider");//Line 106  
  5.     }  
  6.     catch(ClassNotFoundException ex){  
  7.         // JSR-330 API not available - Provider interface simply not supported then.  
  8.     }  
  9. }  

源代码的问题在于:

ClassLoader cl =DefaultListableBeanFactory.class.getClassLoader();返回空!

找了找网上:发现别人也遇到过:

http://stackoverflow.com/questions/2272354/why-do-i-get-a-nullpointerexception-when-initializing-spring

再了解了一下getClassLoader() 的原理:

http://blog.chenlb.com/2009/06/java-classloader-architecture.html

原来是这个DefaultListableBeanFactory通过BootStrap直接加载,getClassLoader()的时候返回null

JDK上也有说明:

"public ClassLoader ‍getClassLoader()返回该类的类加载器。有些实现可能使用 null 来表示引导类加载器。如果该类由引导类加载器加载,则此方法在这类实现中将返回 null。 "

细细想来,原来是这里错了:勾选了System library(added to the boot class path),DefaultListableBeanFactory被当成系统Jar通过BootStrap直接加载


把这个勾去了就好了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值