spring-idol.xml文件中定义如下:
<bean id="saxophone" class="com.springinaction.springidol.Saxophone" />

<bean id="kenney" class="com.springinaction.springidol.Instrumentalist" >
<property name="song" value="Jingle Bells" />
<property name="instrument" ref="saxophone" />
</bean>java文件中代码如下:
public class testSpring {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-idol.xml");
Performer performer = (Performer)ctx.getBean("kenney");
(**)          performer.perform();
}
}
运行时报错:
Playing Jingle Bells : 
Exception in thread "main" java.lang.NullPointerException
at com.springinaction.springidol.Instrumentalist.perform(Instrumentalist.java:10)
at com.springinaction.springidol.testSpring.main(testSpring.java:10)我在(**)处设置了断点,观察到performer 的属性中:
instrument的值为null;
song的值为"Jingle Bells"
我检查了xml文件中的定义,没有错啊?请教各位,谢谢附Instrumentalist.java:
public class Instrumentalist implements Performer{
private Instrument instrument; 
private String song;
public Instrumentalist(){
}
public void perform(){
System.out.println("Playing " + song + " : ");
instrument.play();//因为instrument为空,所以这一句就出现异常了
}
        ......

解决方案 »

  1.   

    你用什么方式  注入值的   怎么看不到你注入值的 设置 或是 代码呢   
    注入方式 :构造器注入setter注入注解注入  你的是哪种 没看到哦
      

  2.   

    bean Instrumentalist 中instrument的get方法写了没有。
      

  3.   

    <property name="instrument" ref="saxophone" />
    改为如下,试试
    <property name="instrument">
       
       <bean ref="saxophone"/></property> setter注入必须是要有的先
      

  4.   

    instrument没有注入进来,set方法写了没
      

  5.   

    注入是通过属性的getter setter方法进行注入的