实体类
package com.hyh.spring.pojo;
import org.springframework.stereotype.Component;
@Component("teacher")
public class Teacher {
private String name;
public Teacher() {
super();
System.out.println("Teacher.Teacher()");
}
public Teacher(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Class [name=" + name + "]";
}
}
spring配置文件:applicationContext-anno.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.hyh.spring.pojo"></context:component-scan>
</beans>
测试类 1:
package com.hyh.spring.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hyh.spring.pojo.Teacher;
public class TestTeahcer {
//获取容器对象
private static ApplicationContext con;
static{
con = new ClassPathXmlApplicationContext("classpath:applicationContext-anno.xml");
}
@Resource(name="teacher")
private Teacher teacher;
@Test
public void test01(){
//Teacher teacher = con.getBean(Teacher.class);
System.out.println(teacher);
}
}
测试结果

实体类的构造方法已经被调用了,说明spring容器中已经创建对象了
为什么通过注@Resource解获取不到值,只能通过getBean()的方式获取,或者测试类写成下面这样:
测试类2
package com.hyh.spring.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hyh.spring.pojo.Teacher;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class TestTeahcer2 {
@Resource(name="teacher")
private Teacher teacher;
@Test
public void test01(){
System.out.println(teacher);
}
}
这个可以获取到teacher对象
是不是跟这两个注解有关
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
在网上查了很多也没弄明白,求解