spring加载xml文件 读取bean时遇到的一个问题

本文记录了在Spring项目中遇到的XML配置文件加载错误的问题。当使用ClassPathXmlApplicationContext尝试加载名为context.xml的配置文件时,由于路径不正确导致FileNotFoundException。解决方法是确保配置文件与加载它的类位于同一目录,或者使用全路径指定配置文件位置。通过调整文件位置或使用Spring推荐的方式,成功解决了问题。此外,项目包含了对事务传播和隔离级别的测试。

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

前段时间遇到一个配置文件的问题,记录下

项目路径图如下:

其中:默认包下面的TestIsolation类,为程序入口:代码如下:

public class TestIsolation {

	
	public static void main(String[] args) {

		ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", TestIsolation.class);
		
		I1Service s1 = (I1Service)ctx.getBean("service1");
		//s1.f1();
		//s1.f3();
		s1.f5();
	}

}


运行此类发现报错:Caused by: java.io.FileNotFoundException: class path resource [context.xml] cannot be opened because it does not exist

原因如下:ClassPathXmlApplicationContext的解释是

Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.

This is a convenience method to load class path resources relative to a given Class. For full flexibility, consider using a GenericApplicationContext with an XmlBeanDefinitionReader and a ClassPathResource argument

配置文件的路径应当要和加载文件的那个类的路径一直,即必须将context.xml放在最外层,也就是默认包下。

再来测试一下:

将TestIsolation类和context.xml同时放入snt.wyb.service包下运行snt.wyb.service.TestIsolation.java类,运行之后正常。

方法二:如果你想在一个类中加入其他包下的配置文件的话,上面那种方法就失效了,spring建议采用如下的方法:

public class TestIsolation {

	
	public static void main(String[] args) {

		//ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", TestIsolation.class);
		
		//I1Service s1 = (I1Service)ctx.getBean("service1");
		//s1.f1();
		//s1.f3();
		//s1.f5();
	   GenericApplicationContext ctx = new GenericApplicationContext();
	   XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
	   xmlReader.loadBeanDefinitions(new ClassPathResource("snt/wyb/service/context.xml"));
	  // PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
	  // propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
	   ctx.refresh();

	   I1Service s1 = (I1Service) ctx.getBean("service1");
	   s1.f5();
	}

}

这样的话,就米有问题了。

还有其他的一些方法,用到了,再在上面添加。

可能大家会觉得我的项目很乱,没办法,我米有新建一个demo。

这个demo是专门用来测试spring的事务传播与隔离级别的。基本上都已实现。

其中x.y.service包测试事务传播,运行方法Required.java    snt.wyb.service 包测试隔离级别,运行方法TestIsolation.java

项目已上传。http://download.youkuaiyun.com/detail/wangyinbin/4272926

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值