当前位置: 首页 > 图文教程 > Java技术 > Web框架 > 获取ApplicationContext的几种方式

Web框架
struts2(三)
struts2(四)
struts2(五)
struts2(六)
Spring中注入概念的简单介绍
深入探讨struts的ActionMessages消息机制(转)
DWR 的 Converter 实现原理简单分析及应用
详解Spring中bean的作用域
AJAX实现级联下拉框
Spring AOP面向方面编程原理:AOP概念
Spring结合Hibernate声明式事务配置
Struts 概述
Ajax 入门简介
Struts配置文件详解
Struts in Spring
Struts 开发的最佳实践
Struts核心标签
开发框架:利用STRUTS实现国际化支持
Struts自定义标签的过程
Struts 框架的基本概念及实现MVC模式的原理

Web框架 中的 获取ApplicationContext的几种方式


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 626 ::
收藏到网摘: n/a

第一种采用类路径的加载方式获取:

    

ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:application.xml");

此处的文件必须位于classpath路径中

  

第二种采用系统文件路径加载的方式获取:

ApplicationContext ctx=new FileSystemXmlApplicationContext("/application.xml");

此处的application.xml必须位于系统中一个具体的位置

 

第三种使用beanfactory加载配置信息:

   Resource r=new ClassPathResource(""); 此处必须为classpath路径中
        Resource res=new FileSystemResource("");必须为文件路径中
       
  BeanFactory bf=new XmlBeanFactory(r);

使用BeanFactory从xml配置文件加载bean:
 

Java code
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class XmlConfigWithBeanFactory {   
      public static void main(String[] args) {
       XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("build/beans.xml"));  
 }
}

使用ApplicationConText从xml配置文件加载bean:
 
Java code
public class XmlConfigWithApplication{
    public static void main(String[] args){
        ApplicationContext application = new ClassPathXmlApplicationContext(beans.xml"));         application.getBean("BeanName");
    }}
ApplicationContext和BeanFacotry相比,提供了更多的扩展功能,但其主要区别在于后者是延迟加载,
如果Bean的某一个属性没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常;
而ApplicationContext则在初始化自身是检验,这样有利于检查所依赖属性是否注入;
所以通常情况下我们选择使用ApplicationContext.