Spring核心IOC源码解读(二)为BeanFactory准备数据
在SpringIOC获取到BeanFactory之后,需要为BeanFactory初始化一些属性,因为此时BeanFactory中只有最基本的BeanDefinition信息,还没有解析BeanDefinition相关的工具,所以在这一步中Spring将SpEL解析器、属性编辑器、Bean后置处理器、系统基本属性等信息依赖到BeanFactory中去。 AbstractApplicationContext.prepareBeanFactory() 方法块代码👇
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { //(1)设置类加载器,用于类加载 beanFactory.setBeanClassLoader(getClassLoader()); //(2)设置SpEL解析器,用于解析Spring EL表达式,解析类似 #{user.userName}的属性 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); //(3)添加属性编辑器 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); //(4)添加Bean后置处理器 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //(5)添加要忽略自动注入的接口 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); ... //(6)注册已经可解析的依赖,主要就是BeanFactory beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); //(7)添加Bean后置处理器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); //(8)注册系统环境属性信息到IOC容器中 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } ... }