您的位置:首页 > 移动开发

spring 的启动 之加载文件 applicationContext.xml

2013-03-22 13:00 387 查看
我们在junit单元测试里写了一个方法,对applicationContext.xml进行手工的调用

package tc.springtest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.hamcrest.SelfDescribing;

import org.apache.commons.logging.LogFactory;
//@Component
// @Transactional
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(locations = { "classpath:config/xml/applicationContext.xml" })
public class test {

@Test
//@Rollback(true)
public void should_return_XXX_when_given_xx(){
System.out.println(123);
ClassPathResource res = new ClassPathResource("classpath:config/xml/applicationContext.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
}

}


可是junit总是报错 说找不到文件applicationContext.xml,令人奇怪的是 如果用
@ContextConfiguration(locations = { "classpath:config/xml/applicationContext.xml" })
程序是可以找到该文件的。单步调试后发现报错的地方在XmlBeanDefinitionReader的第341行loadBeanDefinitions方法里,是在328行
InputStream inputStream = encodedResource.getResource().getInputStream();
抛出的异常,在341行
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
被捕捉到的。



@ContextConfiguration(locations = { "classpath:config/xml/applicationContext.xml" })
打开后进行对比发现loadBeanDefinitions里的参数encodedResource为class path resource [config/xml/applicationContext.xml]

而是用代码进行加载配置文件的时候 encodedResource为class path resource [classpath:config/xml/applicationContext.xml]

两相比较发现多了classpath值。

也就是说 ClassPathResource res = new ClassPathResource 是默认在classpath下进行搜索的。

下一篇我要接着分析一下
ClassPathResource res = new ClassPathResource("config/xml/applicationContext.xml");
的代码过程,以后还要对

@ContextConfiguration(locations = { "classpath:config/xml/applicationContext.xml" })
进行下代码跟踪,看一下两个的具体区别。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐