项目需要使用载入多个xml,方便起见,转载一篇文章作为记录
转自:http://javapub.iteye.com/blog/751772
Spring中加载xml配置文件的方式,我总结的有6种, xml是最常见的spring 应用系统配置源。Spring中的几种容器都支持使用xml装配bean,包括:
XmlBeanFactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext
Resource resource = new ClassPathResource("appcontext.xml"); BeanFactory factory = new XmlBeanFactory(resource);
二、ClassPathXmlApplicationContext 编译路径
ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:appcontext.xml"); // src目录下的 ApplicationContext factory=new ClassPathXmlApplicationContext("appcontext.xml"); ApplicationContext factory=new ClassPathXmlApplicationContext(new String[] {"bean1.xml","bean2.xml"}); // src/conf 目录下的 ApplicationContext factory=new ClassPathXmlApplicationContext("conf/appcontext.xml"); ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml");
ApplicationContext factory=new FileSystemXmlApplicationContext("src/appcontext.xml"); //使用了 classpath: 前缀,作为标志, 这样,FileSystemXmlApplicationContext 也能够读入classpath下的相对路径 ApplicationContext factory=new FileSystemXmlApplicationContext("classpath:appcontext.xml"); ApplicationContext factory=new FileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml"); ApplicationContext factory=new FileSystemXmlApplicationContext("G:/Test/src/appcontext.xml");
ServletContext servletContext = request.getSession().getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext );
五、使用BeanFactory
BeanDefinitionRegistry reg = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(reg); reader.loadBeanDefinitions(new ClassPathResource("bean1.xml")); reader.loadBeanDefinitions(new ClassPathResource("bean2.xml")); BeanFactory bf=(BeanFactory)reg;
<context-param> <!-- Context Configuration locations for Spring XML files --> <param-name>contextConfigLocation</param-name> <param-value> ./WEB-INF/**/Appserver-resources.xml, classpath:config/aer/aerContext.xml, classpath:org/codehaus/xfire/spring/xfire.xml, ./WEB-INF/**/*.spring.xml </param-value> </context-param>