junit测试,使用classpath和file 加载文件的区别

本文探讨了使用Junit测试Spring应用时遇到的配置文件加载问题。通过对比classpath和file前缀的区别,最终确定了正确的配置文件加载方式。

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

用junit测试发现一个问题,怎么加载配置文件?一直都出现这样的错误

ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2d2bf892] to prepare test instance [com.zdwl.test.WriteData@21cc5069]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.zdwl.test.WriteData': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zdwl.dao.impl.JdbcDaoImpl com.zdwl.test.WriteData.jdbcDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.zdwl.dao.impl.JdbcDaoImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}\

以前都是用classpath加载配置文件。

例如:

  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations={"classpath:spring-dao-test.xml"}) 

  public void TestA{

     }

然后发现一直不能将dao接口注入到impl实现类中,其实本质原因还是配置文件没有加载对。

一直在纠结中..............

然后又用

  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations={"file:WEB-INFO/spring-dao-test.xml"}) 

还是不对。

又用classpath*:/spring-dao-test.xml 加载 。。。。还也不能加载。。。我也晕了,咋整都不行呢?

然后又在其他项目里发现测试用的是:file:/spring-dao-test.xml;我就思考为什么用file加载,而不是classpath去加载配置文件。

最终。。。。

   file:加载非编译类的文件系统,即:作为 URL 从文件系统中加载。

   classpath:加载编译的class文件系统,即:从classpath中加载。

 

由于我的配置文件是非编译类配置文件。所以我选择用file:加载配置文件。写全配置文件的绝对路径。

以下是加载配置文件的classpath,file的表格对比:

前缀例子说明

classpath:

classpath:com/myapp/config.xml

从classpath中加载。

file:

file:/data/config.xml

作为 URL 从文件系统中加载。

http:

http://myserver/logo.png

作为 URL 加载。

(none)

/data/config.xml

根据 ApplicationContext 进行判断。

转载于:https://www.cnblogs.com/sumingk/p/5962372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值