关键字
BeanFactory
ApplicationContext
创建Bean的三种方法
Bean的作用域
Bean的生命周期
Bean的XML元数据配置
自动扫描管理Bean
对于Spring框架开发而言,BeanFactory和ApplicationContext无疑是最基础的两个类。那么这篇文章就介绍下。
一 BeanFactory
接口BeanFactory(org.springframework.beans.BeanFactory),其职责是:处理Bean的初始化,定位,配置应用程序中的对象以及建立这些对象的依赖。Bean对象的依赖是通过元数据来描述。通过BeanFactoryAware类实现。比较常用的子接口为XMLBeanFactory。
对于单个文件的读取方法有如下两种:
1)
Java代码 Resource resource = new FileSystemResource(“beans.xml”); BeanFactory factory = new XmlBeanFactory(resource); Resource resource = new FileSystemResource(“beans.xml”);
BeanFactory factory = new XmlBeanFactory(resource);
2)
Java代码 ClassPathResource resource = new ClassPathResource(“beans.xml”); BeanFactory factory = new XmlBeanFactory(resource); ClassPathResource resource = new ClassPathResource(“beans.xml”);
BeanFactory factory = new XmlBeanFactory(resource);
当需要从多个文件中加载一个BeanFactory实例时候,可以像如下使用:
Java代码 ApplicationContext ctx= new ClassPathXmlApplicationContext(new String[]{“beans.xml”,”application.xml”}); BeanFactory factory =ctx; ApplicationContext ctx= new ClassPathXmlApplicationContext(new String[]{“beans.xml”,”application.xml”});
BeanFactory factory =ctx;
而Bean Factory通过Bean definition reader从多个文件中读取Bean定义,这样的话,我们可以这么处理,即组成基于XML配置元数据可以做如下配置:
Xml代码