Spring的注入方式

3 篇文章 0 订阅

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(空指针异常)

@Autowired注解

default-autowired属性加InitializingBean接口

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值