首页 > 代码库 > Spring中BeanFactory和ApplicationContext的区别

Spring中BeanFactory和ApplicationContext的区别

我用一个例子去测试BeanFactory和ApplicationContext的区别

首先建立一个bean

public class User {
//声明无参构造,打印一句话,监测对象创建时机
public User(){ System.out.println("User对象初始化"); }}

然后再建立测试类

public class UserTest {    @Test    public void ApplicationContexttest(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");    }    @Test    public void BeanFactorytest(){        Resource resource=new PathResource("applicationContext.xml");        BeanFactory beanFactory=new XmlBeanFactory(resource);    }}

配置xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">

<bean name="user" class="bean.entity.User"></bean>

</beans>

 

执行 ApplicationContexttest()方法

结果:

技术分享

说明user对象在ApplicationContext对象创建时user对象就已经初始化

执行BeanFactorytest()方法 

结果:

技术分享

BeanFactory对象初始化时并没有初始化user对象

然后向两个方法添加获取对象的代码

public class UserTest {    @Test    public void ApplicationContexttest(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        System.out.println(context.getBean("user"));        System.out.println(context.getBean("user"));    }    @Test    public void BeanFactorytest(){        Resource resource=new ClassPathResource("applicationContext.xml");        BeanFactory beanFactory=new XmlBeanFactory(resource);        System.out.println(beanFactory.getBean("user"));        System.out.println(beanFactory.getBean("user"));    }}

执行 ApplicationContexttest()方法

结果:

技术分享

两次对象内存地址一致

执行BeanFactorytest()方法 

结果:

技术分享

在执行getBean()方法时才创建user对象

 

Spring中BeanFactory和ApplicationContext的区别