前段时间遇到一个配置文件的问题,记录下
项目路径图如下:
其中:默认包下面的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