03.Spring的ApplicationContext
简介
ApplicationContext 称为Spring容器,内部封装了BeanFactory,比BeanFactory功能更丰富更强大,使用ApplicationContext 进行开发时,xml配置文件的名称习惯写成applicationContext.xml
1.1 ApplicationContext的核心代码
bean.xml的配置和其他部分代码请参考 02.Spring的BeanFactory
这里只展示ApplicationContext 替代BeanFactory的代码
文件路径:
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置UserServiceImpl-->
<bean id="userService" class="com.test.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!--配置UserDaoImpl-->
<bean id="userDao" class="com.test.dao.impl.UserDaoImpl"></bean>
</beans>
测试核心代码:
public class ApplicationContextTest {
public static void main(String[] args) throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = applicationContext.getBean(UserService.class);
System.out.println(userService);
}
}
1.2 BeanFactory与ApplicationContext的关系
ApplicationContext除了继承了BeanFactory外,还继承了ApplicationEventPublisher(事件发布器)、ResouresPatternResolver(资源解析器)、MessageSource(消息资源)等。但是ApplicationContext的核心功能还是BeanFactory。
总结:
1)BeanFactory是Spring的早期接口,称为Spring的Bean工厂,ApplicationContext是后期更高级接口,称之为Spring 容器;
2)ApplicationContext在BeanFactory基础上对功能进行了扩展,例如:监听功能、国际化功能等。BeanFactory的API更偏向底层,ApplicationContext的API大多数是对这些底层API的封装;
3)Bean创建的主要逻辑和功能都被封装在BeanFactory中,ApplicationContext不仅继承了BeanFactory,而且ApplicationContext内部还维护着BeanFactory的引用,所以,ApplicationContext与BeanFactory既有继承关系,又有融合关系。
4)Bean的初始化时机不同,原始BeanFactory是在首次调用getBean时才进行Bean的创建,而ApplicationContext则是配置文件加载,容器一创建就将Bean都实例化并初始化好。
1.3 验证初始化时机
applicationContext内部维护着beanFactory的引用,断点查看beanFactory内部维护的属性
下面验证BeanFactory和ApplicationContext对Bean的初始化时机
断点观察,BeanFactory方式时,xml配置加载完成后,单例池为空,没有进行Bean创建
首次调用getBean时才进行Bean的创建,即延迟加载
ApplicationContext方式,配置文件加载后,Bean实例化并且初始化完成,当调用getBean时直接从单例池中获取Bean实例返回