SpringFramework核心技术一(IOC:BeanFactory)

什么是BeanFactory

这BeanFactory为Spring的IoC功能提供了基础,但它只能直接用于与其他第三方框架的集成,现在对于Spring的大多数用户来说,它本质上是历史性的。在BeanFactory与相关的接口,如BeanFactoryAware,InitializingBean,DisposableBean,仍然存在于Spring为向后兼容性与大量与Spring集成第三方框架的目的。通常第三方组件不能使用更多的现代等价物,例如@PostConstruct或@PreDestroy为了避免依赖JSR-250。


一、使用BeanFactory 还是 ApplicationContext?

使用ApplicationContext,除非你有更好的理由,不去使用他?

由于ApplicationContext包含了所有功能BeanFactory,所以比BeanFactory更建议使用ApplicationContext。除此之外,除了少数情况外,例如在资源受限的设备上运行的嵌入式应用程序,这些应用程序的内存消耗可能很重要,少数几千字节可能会产生差异,可以使用BeanFactory。但是,对于大多数典型的企业应用程序和系统,这ApplicationContext是您将要使用的。Spring 大量使用BeanPostProcessor扩展点(以影响代理等)。如果您仅使用普通BeanFactory,则交易和AOP等相当一部分支持将不会生效,至少在您没有采取某些额外步骤的情况下不会生效。这种情况可能会令人困惑,因为配置没有任何问题。

下表列出了提供的功能BeanFactory和 ApplicationContext接口和实现。
功能矩阵:

特征 BeanFactory BeanFactory
Bean实例化/布线
自动BeanPostProcessor注册 没有
自动BeanFactoryPostProcessor注册 没有
方便的MessageSource访问(国际化) 没有
ApplicationEvent 出版物 没有

要使用实现明确注册bean后处理器BeanFactory,您需要编写如下代码:

DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
// populate the factory with bean definitions

// now register any needed BeanPostProcessor instances
MyBeanPostProcessor postProcessor = new MyBeanPostProcessor();
factory.addBeanPostProcessor(postProcessor);

// now start using the factory

要BeanFactoryPostProcessor在使用BeanFactory 实现时明确注册,您必须编写如下代码:

DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(new FileSystemResource("beans.xml"));

// bring in some property values from a Properties file
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));

// now actually do the replacement
cfg.postProcessBeanFactory(factory);

在这两种情况下,显式注册步骤都很不方便,这是 绝大多数Spring支持的应用程序ApplicationContext中优先于各种实现的各种实现的一个原因BeanFactory,特别是在使用BeanFactoryPostProcessors和BeanPostProcessors时。这些机制实现了重要的功能,如资产占位符替换和AOP。

结语:在这里只需要知道ApplicationContext包含了BeanFactory的所有功能就可以了。

猜你喜欢

转载自blog.csdn.net/wd2014610/article/details/80664777
今日推荐