Spring配置文件(2)配置方式

由於目前正在從事一個項目,項目中一個需求就是全部的功能都是插件的形式裝入系統,這就須要利用Spring去動態加載某一位置下的配置文件,因此就總結 了下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>元素來指定多個配置文件位置,其配置以下:
java

Java代碼  收藏代碼web

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

這個方法加載配置文件的前提是已經知道配置文件在哪裏,雖然能夠利用「*」通配符,但靈活度有限。spring

相關文章
相關標籤/搜索