pring中的几种容器都支持使用xml装配bean,包括:
XmlBeanFactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext
1. XmlBeanFactory 引用资源
Resource resource = new ClassPathResource("applicationContext-jms.xml");
BeanFactory factory = new XmlBeanFactory(resource);
2. ClassPathXmlApplicationContext 编译路径
// src
ApplicationContext factory = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext factory = new ClassPathXmlApplicationContext(new String[] {"bean1.xml", "bean2.xml"});
// src/conf
ApplicationContext factory = new ClassPathXmlApplicationContext("conf/bean.xml");
ApplicationContext factory = new ClassPathXmlApplicationContext("file:D:/Biubiu.Net/src/bean.xml");
3. 用文件系统的路径
ApplicationContext factory = new FileSystemXmlApplicationContext("src/appcontext.xml");
// 使用了classpath: 前缀作为标志; 这样FileSystemXmlApplicationContext也能够读入classpath下的相对路径
ApplicationContext factory = new FileSystemXmlApplicationContext("classpath:appcontext.xml");
ApplicationContext factory = new FileSystemXmlApplicationContext("file:D:/Biubiu.Net/src/bean.xml");
ApplicationContext factory = new FileSystemXmlApplicationContext("G:/Biubiu.Net/src/appcontext.xml");
4. XmlWebApplicationContext是专为Web工程定制的
ServletContext servletContext = request.getSession().getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
5. 使用BeanFactory
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("bean1.xml"));
reader.loadBeanDefinitions(new ClassPathResource("bean2.xml"));
BeanFactory beanFactory = (BeanFactory)reg;
6. Web 应用启动时加载多个配置文件
通过ContextLoaderListener也可加载多个配置文件,在web.xml文件中利用元素来指定多个配置文件位置,其配置如下:
<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>