spring 属性注入

图片描述

配置文件如上图

CDPlayer 代码:
package springdemo;

import org.springframework.beans.factory.annotation.Autowired;

public class CDplayer {

private CD cdd;
@Autowired
public void setCdd(CD c){
    this.cdd=c;
}
public void play(){
    System.out.println(cdd);//跟踪cdd输出是null
        cdd.play();
}


}

测试代码:
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import springdemo.CDplayer;

public class CDtest {

@Test
public void goCd(){
    ClassPathXmlApplicationContext ct = new ClassPathXmlApplicationContext("application.xml");
    CDplayer cp =(CDplayer) ct.getBean("cp");
    cp.play();
}

}
怎么一直报空指针异常搞不明白,

@Autowired
public void setCdd(CD c){
    this.cdd=c;
} 这个方法不是已经把CD注入进来了吗? 按理说下面调用cdd的时候不应该为空啊,新手刚接触  实在困惑

直接这样写:
public class CDplayer {

@Autowired
private CD cdd;


public void play(){
    System.out.println(cdd);//得到还是为空的
        cdd.play();
}

}
或者这样:
图片描述public class CDplayer {

private CD cdd;

public void play(){
    System.out.println(cdd);
        cdd.play();
}

}

为什么换成下面的代码就可以了?配置文件xml是上面 cdd报红色错误的这个配置
public class CDplayer {

private CD cdd;

@Autowired
public void setCdd(CD c){
    this.cdd=c;
}
public void play(){
    System.out.println(cdd);
        cdd.play();
}

}

阅读 2.7k
3 个回答

谢邀,因为你的注入是通过注解实现的,所以应该在配置文件中显示声明<context:annotation-config />

p小写了。。。注意看黄色的警告提示。


题主更新了。
注入改成这个
@Autowired("cd")
private CD cdd;

@Component
public class CDplayer {

加上@Component再尝试尝试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题