BeanFactory工厂

Core模块主要的功能是实现了反向控制(Inversion of Control)与依赖注入(Denpendency Injection)、Bean配置以及加载。

Beans为Spring里的各种对象,一般要配置在Spring的配置文件中;BeanFactory为创建Beans的factory,Spring通过BeanFactory加载各种Beans;BeanDefinition为Bean在配置中的定义,一般要定义id与class;ApplicationContext代表配置文件。

BeanFactory工厂

BeanFactory是实例化、管理众多的容器。

BeanFactory可用接口org.springframework.beans.factory.BeanFactory表示。

BeanFactory最常见的实现类为XmlBeanFactory。XmlBeanFactory可以加载xml的配置文件。

实例化BeanFactory

  Web程序加载时候自动实例化BeanFactory,并加载所有Beans,并将Bean设置到各个组件资源中。

  java桌面程序中,需要从BeanFactory获取Bean,所以需要实例化BeanFactory。

例如:

ClassPathResource res=new ClassPathResource("applicationContext.xml");//获取配置资源,一般使用的是相对路径
XmlBeanFactory beanFactory=new XmlBeanFactory(res);//实例化工厂对象

IService hello=(IService) factory.getBean("service");//从工厂中获取对象
...//其他代码略
Beanfactory.destorySingletons();//销毁实例化的工厂对象

加载多个配置文件

public static void main(String[] args) {
        ClassPathXmlApplicationContext appContext=new ClassPathXmlApplicationContext(
        new String[]{"com/test/applicationContext.xml","com/test/applicationContext_2.xml"}        
        );
        BeanFactory factory=(BeanFactory)appContext;
        Dog d=(Dog) factory.getBean("dog");
        System.out.println(d.getName()+"	"+d.getAge());
    }
原文地址:https://www.cnblogs.com/aigeileshei/p/5458474.html