苏铭客

导航

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

用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 进行判断。

posted on 2016-10-14 22:39  苏铭客  阅读(6960)  评论(0编辑  收藏  举报