Junite 中 测试@Autowired 无法生效的原因

本文展示了通过ClassPathXmlApplicationContext和@Autowired测试IOC的例子。测试@Autowired时遇到无法自动注入Bean的问题,经检查需引入spring - test框架并加载bean文件,最终发现是spring - test版本太高,引入4.1.3版本后问题解决。

package IOCReview;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**  
* @ClassName: IOC入门Test  
* @Description: TODO(这里用一句话描述这个类的作用)  
* @author Administrator  
* @date 2019年5月15日  
*    
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! 
@ContextConfiguration({"classpath:applicationContext.xml"})  //用于加载bean
public class IOCTest {
    
    @Autowired
    public Car car;
    
    @Test
    public void testName() throws Exception {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao dao=(UserDao) context.getBean("UserDao");
        dao.save();
    }
    
    @Test
    public void testCar() throws Exception {
        System.out.println(car.getName()+"   "+car.getPrice());
    }
}

 

 

以上是我通过ClassPathXmlApplicationContext 以及  @Autowired 测试IOC的例子

后面测试@Autowired  遇到困难,无法自动注入Bean

经过检查,发现首先要映入spring-test的框架,其次要加载bean文件,这是我在网上查到的

不过我测试的时候还是不行,后面检查发现是spring-test的版本太高了,最后引入4.1.3才OK

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! 
@ContextConfiguration({"classpath:applicationContext.xml"})  //用于加载bean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值