前提:

导入junit-4.12.jar和hamcrest-all-1.3.jar
hamcrest-all-1.3.jarjunit-4.12.jar

创建文件:

1.创建JunitTest类
2.创建model类
3.创建applicationContext.xml

代码:

model.java

  1. package com.how2java.bean;
  2. import org.springframework.stereotype.Repository;
  3. @Repository
  4. public class model {
  5. private String modelID;
  6. public String getModelID() {
  7. return modelID;
  8. }
  9. public void setModelID(String modelID) {
  10. this.modelID = modelID;
  11. }
  12. }

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:p="http://www.springframework.org/schema/p"
  7. xmlns:context="http://www.springframework.org/schema/context"
  8. xsi:schemaLocation="
  9. http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop.xsd">
  15. <bean id="model" name="model" class="com.how2java.bean.model">
  16. <property name="modelID" value="This is a modelID"/>
  17. </bean>
  18. <bean id="model2" name="model2" class="com.how2java.bean.model">
  19. <property name="modelID" value="This is a modelID2"/>
  20. </bean>
  21. </beans>

JunitTest.java

  1. package com.how2java.test;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Qualifier;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. import com.how2java.bean.model;
  9. @RunWith(SpringJUnit4ClassRunner.class)
  10. @ContextConfiguration("classpath:applicationContext.xml")
  11. public class JunitTest {
  12. @Autowired()
  13. @Qualifier("model")
  14. model c;
  15. @Test
  16. public void test(){
  17. System.out.println(c.getModelID());
  18. }
  19. }

要点:

1.@Autowired是根据类型匹配,如果有多个匹配的,需要配合@Qualifier来匹配名称。如果有多个匹配的,且没有写@Qualifier,会报错。
2.@RunWith,表示这是一个Spring的测试类。
3. @ContextConfiguration(“classpath:applicationContext.xml”),定位Spring的配置文件。
4.@Test,测试逻辑。