@Resource拿不到bean。求解

o0caicaihua 2014-10-11 06:47:36
手写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,咋回事啊
...全文
1019 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Magical茏 2014-10-11
  • 打赏
  • 举报
回复
引用 1 楼 littlebrain4solving 的回复:
不太清楚,我猜@Resource应该只对@Repository管用吧! 建议你用@Autowire或者把Student的注解使用@Repository看看
你根本就没用过注解 楼主你要知道执行的顺序 创建一个对象的时候 ,首先 是 对成员变量初始化 然后 是 调用构造函数 构造函数调用完毕后这个对象才算真正的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
scmod 2014-10-11
  • 打赏
  • 举报
回复
Autowire没用的话你输出放main里面看看 可能构造方法执行时候还没注入bean
影游 2014-10-11
  • 打赏
  • 举报
回复
你既然使用Resource,应该是想用bean name 装载吧,可以如下试一试, @service("类名") @resource(name = "类名") 或者使用@AutoWare,自动装载...
  • 打赏
  • 举报
回复
不太清楚,我猜@Resource应该只对@Repository管用吧! 建议你用@Autowire或者把Student的注解使用@Repository看看

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧