81,091
社区成员
发帖
与我相关
我的任务
分享
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 + "]";
}
}
<?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>
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);
}
}
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);
}
}