Spring测试类自动注入(Autowire)问题

首先测试类上方要加入

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/*.xml")

其中SpringJUnit4ClassRunner的pom依赖为

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.25.RELEASE</version>
      <scope>test</scope>
    </dependency>

注意junit的版本为4.12及以上,不然会报错

ContextConfiguration中locations为spring及springMVC配置文件

注意,测试类调用的类中如果包含自动注入的对象,那么该类生成的对象必须使用自动注入,不能够new出来,否则该类中的自动注入对象会报空指针异常。
例如,在Test类中使用了UserController类,而UserController类中调用了自动注入的UserService类,那么UserService的对象会出现空指针异常。

这是因为加了@Component的注解的类通过spring配置文件扫描后会交由IoC容器管理,自动创建对象,而自己new出来的类是不会注入到容器的。如果有需要,也可以自行编写工具类,将生成的类主动注入到ApplicationContext容器中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值