在下面的项目里演示一下两种测试方式,Junit测试和Spring自带的SpringJunit单元测试,后者需要导入jar包;
首先创建一个简单的java工程:
Junit测试类1:
public class TestPersonJunit {
BeanFactory bf;
@Before
public void before() {
// TODO Auto-generated method stub
//F4(接口实现类)
System.out.println("before");
bf=new ClassPathXmlApplicationContext("applicationContext3.xml");
}
@Test
public void test() {
System.out.println("test");
Person p=(Person) bf.getBean("person");
System.out.println(p);
}
@After
public void after() {
System.out.println("after");
}
}
SpringJunit测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/applicationContext3.xml")
public class TestPersonSpringJunit {
@Autowired
// @Qualifier(value="")
Person p;
@Test
public void test() {
System.out.println(p);
}
}
解析文件applicationContext3.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.rjs.entity.Person" id="person">
<!-- constructor-arg构造的参数指定 index="0"第一个参数 index="1" 第二个参数-->
<constructor-arg index="0" value="1"></constructor-arg>
<constructor-arg index="1" value="小明"></constructor-arg>
</bean>
<!-- <bean class="com.rjs.entity.Person" id="person2">
constructor-arg构造的参数指定 参数name来指定
<constructor-arg name="id" value="1"></constructor-arg>
<constructor-arg name="name" value="小明"></constructor-arg>
</bean> -->
</beans>
测试结果: