手写ctx.getBean("student"); 就可以拿到对象,但是我用@Resource方法拿总输出的 null
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="cn.kkk"/>
</beans>
package cn.kkk;
import org.springframework.stereotype.Service;
@Service
public class Student {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
测试类
package cn.kkk;
import javax.annotation.Resource;
@Controller
public class Test {
@Resource
public Student stu;
public Test()
{
System.out.println(stu);
}
public static void main(String[] args) {
new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
输出 null,咋回事啊
------解决思路----------------------
你根本就没用过注解
楼主你要知道执行的顺序
创建一个对象的时候
,首先 是 对成员变量初始化
然后 是 调用构造函数
构造函数调用完毕后这个对象才算真正的new出来
然后再通过反射注入对象
public Student student;
public Test() {
System.out.println(student);
}
@Resource
public void setStudent(Student student) {
this.student = student;
System.out.println(student + "--------set");
}
打印
null
cn.Student@b8c3679--------set