junit

配置文件放到哪都是可以取到的。。。。。。

1、web项目applicationContext.xml在webRoot/web-info/下

public class ChaneTest {

@Test
public void test() {
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"WebRoot/WEB-INF/applicationContext.xml"));
//还可以加载其它相关配置文件 factory.add()
Service service = (Service) factory.getBean("service");

int i = service.findDates().size();
System.out.println(i);
}


}

2、applicationContext.xml在src目录下

ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");

一:ClassPathXmlApplicationContext
1.没有前缀:默认为项目的classpath下相对路径
   ApplicationContext appCt = new ClassPathXmlApplicationContext("app.spring.xml");

2.前缀classpath:表示的是项目的classpath下相对路径
   ApplicationContext appCt = new ClassPathXmlApplicationContext("classpath:app.spring.xml");

3.使用前缀file 表示的是文件的绝对路径
   ApplicationContext appCt = new ClassPathXmlApplicationContext("file:D:/app.spring.xml");

4.可以同时加载多个文件
  String[] xmlCfg = new String[] { "classpath:base.spring.xml","app.spring.xml"};
  ApplicationContext appCt = new ClassPathXmlApplicationContext(xmlCfg);

5.使用通配符加载所有符合要求的文件
  ApplicationContext appCt = new ClassPathXmlApplicationContext("*.spring.xml");

二:FileSystemXmlApplicationContext
1.默认为项目工作路径 即项目的根目录
ApplicationContext appCt2 = new FileSystemXmlApplicationContext("src/main/resources/app.spring.xml");

2.前缀classpath:表示的是项目的classpath下相对路径
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:app.spring.xml");

3.使用前缀file 表示的是文件的绝对路径
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("file:D:/app.spring.xml");
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("D:/app.spring.xml");

4.可以同时加载多个文件
  String[] xmlCfg = new String[] { "src/main/resources/base.spring.xml","classpath:app.spring.xml"};
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext(xmlCfg);

5.使用通配符加载所有符合要求的文件
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:*.spring.xml");



原文地址:https://www.cnblogs.com/fangj/p/2232842.html