初学Spring之整合Junit时易犯的错误

本文分享了一位开发者在学习Spring框架整合Junit时遇到的典型错误:将@ContextConfiguration误写为@Configuration,导致无法加载Spring配置文件。通过对比正确代码,强调了正确使用注解的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来说说自己学spring时整合Junit易犯的一个错吧(感觉是自己学习态度问题)
先上错误代码吧

package cn.itcast.springAOP.demo5;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itcast.springAOP.demo3.CustomerService;

@RunWith(SpringJUnit4ClassRunner.class)
@Configuration("classpath:applicationContext2.xml")
public class SpringTest1 {
	@Autowired
	private CustomerService customerService;

	@Test
	public void demo() {
		customerService.add();
	}
}

运行结果:
在这里插入图片描述
可以看到报错一直是无法加载配置文件,然而检查了好多遍都没有找到问题!最后通过对比别人的代码终于找到了错误,下面是正确代码!

package cn.itcast.springAOP.demo5;

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

import cn.itcast.springAOP.demo3.CustomerService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
public class SpringTest1 {
	@Autowired
	private CustomerService customerService;

	@Test
	public void demo() {
		customerService.add();
	}
}

修改后的执行结果:
在这里插入图片描述
有没有发现是哪里错了呢?
如果还没有认真看看你就会发现:是把@ContextConfiguration注解弄成@Configuration了,导致加载不了spring配置.
终归还是态度问题吧!!共勉!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姑苏_IT

创作不易,谢你打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值