目录
1.BeanFactory or ApplicationContext?
BeanFactory
BeanFactory提供了IoC容器功能的根本基础,但它只在与第三方框架的集成中使用,对于大多数用户来说BeanFactory已经成为了历史。
BeanFactory以及相关的接口(eg:BeanFactoryAware、InitializingBean、DisposableBean)仍然存在于Spring中的主要原因是为了与大量集成了Spring的第三方框架向后兼容。
1.BeanFactory or ApplicationContext?
除非有更好的理由不这么做,否则使用ApplicationContext。
ApplicationContext完全包含了BeanFactory的功能。
Spring大量使用了BeanPostProcessor扩展点。如果只使用简单的BeanFactory,相当数量的功能(eg:AOP与事务)支持将无法运作,至少需要添加额外的步骤。
BeanFactory注册pos-processor
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
BeanFactory注册BeanFactoryPostProcessor
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);
note:BeanFactory的配置与ApplicationContext相比,较为繁琐不便。