package testone.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
public class TestStudent {
int id;
String name;
public TestStudent(String name) {
this.name = name;
}
public TestStudent(int id, String name) {
this.id = id;
this.name = name;
}
public TestStudent() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "TestStudent" class="testone.bean.TestStudent">
<constructor-arg name="id" type="int" value="1"/>
<constructor-arg name="name" type="java.lang.String" value="lisi"/>
</bean>
<bean id = "testStudent2" class="testone.bean.TestStudent">
<constructor-arg name="name" type="java.lang.String" value="wangwu"/>
</bean>
</beans>
package testone.bean;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.support.XmlWebApplicationContext;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/spring/demo.xml")
public class TestStudentTest {
@Autowired
@Qualifier("testStudent2")
private TestStudent testStudent;
@Test
public void TestStudentTest() {
System.out.println(testStudent.getName());
}
}
直接在java包里面测试不在Junit4中:
package testone.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/demo.xml");
TestStudent student = (TestStudent) context.getBean("testStudent2");
System.out.println(student.getName());
}
}