Spring中的BeanFactory和ApplicationContext的区别

时间:2022-09-08 21:37:47

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

首先建立一个bean

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

然后再建立测试类

Spring中的BeanFactory和ApplicationContext的区别
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);
}
}
Spring中的BeanFactory和ApplicationContext的区别

配置xml

Spring中的BeanFactory和ApplicationContext的区别
<?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>
Spring中的BeanFactory和ApplicationContext的区别

 

执行 ApplicationContexttest()方法

结果:

Spring中的BeanFactory和ApplicationContext的区别

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

执行BeanFactorytest()方法 

结果:

Spring中的BeanFactory和ApplicationContext的区别

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

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

Spring中的BeanFactory和ApplicationContext的区别
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"));
}
}
Spring中的BeanFactory和ApplicationContext的区别

执行 ApplicationContexttest()方法

结果:

Spring中的BeanFactory和ApplicationContext的区别

两次对象内存地址一致

执行BeanFactorytest()方法 

结果:

Spring中的BeanFactory和ApplicationContext的区别

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