zoukankan      html  css  js  c++  java
  • Beanfactory与ApplicationContext

    Spring提供了容器实现的两种方式: 

      Bean工厂(BeanFactory接口),提供了基础的依赖注入支持;

      应用上下文(ApplicationContext接口),建立在Bean工厂基础之上,提供了系统架构服务。

    现阶段,企业开发在选择上更加倾向于ApplicationContext接口,因为ApplicationContext接口涵盖了BeanFactory接口,如果使用一个普通的BeanFactory接口,很多其他的功能将不会起作用,如Spring的事物transcation和AOP都不会起作用;但是Beanfactory为什么又是一种没有被舍弃的方式!在有些情况下,比如运行在资源受限设备的内嵌式的应用,对内存消耗很大,几百兆的内存也会有很大的影响,此时BeanFactory是更优的选择。

    使用BeanFactory获取bean的方式(常用XmlBeanFactory)

    在Spring中有几种BeanFactory的实现。其中最常使用的是org.springframework.beans.factory.xml.XmlBeanFactory,它根据XML文件中的定义装在Bean。要创建XmlBeanFactory,需要传递一个org.springframework.core.io.Resource实例给构造函数。此Resource对象提供XML文件给工厂。

    有以下几种方式配置XML源:

      org.springframework.core.io.ByteArrayResource

      org.springframework.core.io.ClassPathResource

      org.springframework.core.io.DescriptiveResource

      org.springframework.core.io.FileSystemResource

      org.springframework.core.io.InputStreamResource

    比如使用FileSystemResource创建一个XmlBeanFactory:

      BeanFactory factory = XmlBeanFactory(new InputStreamResource("D:userBean.xml"));

      UserBean userBean = (UserBean)factory.getBean("userBean");

    三、使用ApplicationContext获取Bean(三种常用实现)

      表面上,ApplicationContext和BeanFactory差不多。两者都是载入Bean定义信息,装配Bean,根据需要分发Bean。

    但是,ApplicationContext提供了更多功能:

      1、提供了文本信息解析工具,包括对国际化(I18N)的支持。

      2、提供了载入文件资源的通用方法,如载入图片。

      3、可以向注册为监听器的Bean发送事件。

    因此,我们应该更多的使用ApplicationContext,而不是BeanFactory。

    注意:二者的关系是ApplicationContext接口扩展于BeanFactory

    ApplicationContext的诸多实现中,以下三种经常用到:

      ClassPathXmlApplicationContext

      FileSystemXmlApplicationContext

      XmlWebApplicationContext

    第一种和第二种的区别在于,ClassPath可以在整个类路径(包括JAR文件)中寻找定义Bean的XML文件;而FileSystem只能在指定路径中寻找。

      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext*.xml");

      ApplicationContext context = new FileSystemXmlApplicationContext("D:applicationContext*.xml");

      

  • 相关阅读:
    IXmlSerializable With WCFData Transfer in Service Contracts
    Difference Between XmlSerialization and BinarySerialization
    Using XmlSerializer (using Attributes like XmlElement , XmlAttribute etc ) Data Transfer in Service Contracts
    Introducing XML Serialization
    Version Tolerant Serialization
    Which binding is bestWCF Bindings
    Data Transfer in Service Contracts
    DataContract KnownTypeData Transfer in Service Contracts
    Using the Message ClassData Transfer in Service Contracts
    DataContract POCO SupportData Transfer in Service Contracts
  • 原文地址:https://www.cnblogs.com/shirandedan/p/6209471.html
Copyright © 2011-2022 走看看