ApplicationContext
@Resource注解
在Spring容器中通过name或者type来查找Bean的实例,使用该注解时Spring容器要已经加载了该bean。即xxxbean.xml中配置的bean已经被Spring容器初始化,例如通过ApplicationContext加载该配置文件。
对于测试,可以通过使用Spring提供的@RunWith和@ContextConfiguration注解来模拟容器初始化。例如:
/*
* Copyright (c) 2016, 2101, Alibaba Group. All rights reserved.
*/
package com.taobao.payment.pay;
import com.taobao.hsf.standalone.HSFEasyStarter;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created with IntelliJ IDEA, love and passion of Huijin Payment Team.
*
* @author: xiwei.cw
* Date: 2016/6/15
* Time: 16:52
* Description: 基础的服务测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:META-INF/spring/spring-dao.xml",
"classpath*:META-INF/spring/spring-delegate-support.xml",
"classpath*:META-INF/spring/spring-proxy-provider.xml",
"classpath*:META-INF/spring/spring-hsf-consumer-channel.xml",
"classpath*:META-INF/spring/spring-persistence.xml",
"classpath*:META-INF/spring/spring-tddl.xml",
"classpath*:META-INF/spring/spring-domain.xml",
"classpath*:META-INF/spring/spring-notify-publisher.xml",
"classpath*:spring/spring-service-4test.xml"})
public class BaseServiceTest {
static{
System.setProperty("project.name", "payment");
//LogUtil.info("##################startpando######");
HSFEasyStarter.startWithVersion("2.1.0.7");
}
}
这样使用@Resource就不会报npe(空指针异常)