Spring中加載xml配置文件的方式

項目需要使用載入多個xml,方便起見,轉載一篇文章作爲記錄

轉自:http://javapub.iteye.com/blog/751772


Spring中加載xml配置文件的方式,我總結的有6種, xml是最常見的spring 應用系統配置源。Spring中的幾種容器都支持使用xml裝配bean,包括:

XmlBeanFactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext


一、 XmlBeanFactory 引用資源
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");

四、XmlWebApplicationContext是專爲Web工程定製的

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; 

六、Web 應用啓動時加載多個配置文件
通過ContextLoaderListener 也可加載多個配置文件,在web.xml文件中利用
<context-pararn>元素來指定多個配置文件位置,其配置如下:

<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> 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章