spring单元测试junit及spring配置

来源:互联网 发布:mac电脑淘宝秒杀软件 编辑:程序博客网 时间:2024/05/16 19:18

完整的junit单元测试及spring配置

XXXXTest.java

private static ClassPathXmlApplicationContext ctx;

/**
  * 装入spring配置文件,注入bean
  * @throws Exception
  */

@Before
 public void setUp() throws Exception {
  try {
   String[] configLocation = {
   "classpath*:spring/applicationContext-*.xml" };
   ctx = new ClassPathXmlApplicationContext(configLocation);
  } catch (Exception e) {
   e.printStackTrace();
   throw e;
  }
 }

 

@Test
 public void test() {
  try {
   ClassName aclassobj= (ClassName)ctx.getBean("xmlClassName");
   aclassobj.method();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 

spring配置文件

1、applicationContext-bean.xml

配置xmlClassName中使用到的成员变量,自动装入,注意ClassName中要有set,get函数

如:

<bean id="xmlClassName" class="ClassNamePackage">
     <property name="="***service" ref="***service"/>
     <property name="userName" value="${userName}"/>//配置文件中注入
 </bean>

 

2、applicationContext-service.xml

<bean id="="***service" class="="***servicePackage" >
  <property name="Path" value="$path}" />//配置文件中注入
 </bean>

 

 

 

0 0