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

我们在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" })  
进行下代码跟踪,看一下两个的具体区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值