1、源码解析
prepareBeanFactory(beanFactory)是beanFactory的准备工作,主要是对beanFactory的各种属性做填充。1 // beanFactory的准备工作,配置容器上下文,如容器的类加载器和后置处理器 2 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { 3 4 // 设置当前context的classloader为beanFactory的classloader 5 beanFactory.setBeanClassLoader(getClassLoader()); 6 // 设置表达式语言处理器 7 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); 8 // 为beanFactory增加一个默认的propertyEditor,这个主要是对bean的属性等设置管理的一个工具类 9 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); 10 11 // 添加beanPostProcessor,ApplicationContextAwareProcessor此类用来完成某些Aware对象的注入 12 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); 13 // 设置要忽略自动装配的接口,这些接口的实现是由容器通过set方法进行注入的,所以在使用autowire进行注入的时候需要将这些接口进行忽略 14 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); 15 beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); 16 beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); 17 beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); 18 beanFactory.ignoreDependencyInterface(MessageSourceAware.class); 19 beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); 20 21 // 设置几个自动装配的特殊规则,当在进行ioc初始化的如果有多个实现,那么就使用指定的对象进行注入 22 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); 23 beanFactory.registerResolvableDependency(ResourceLoader.class, this); 24 beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); 25 beanFactory.registerResolvableDependency(ApplicationContext.class, this); 26 27 // 注册BeanPostProcessor, 在registerBeanPostProcessors做处理 28 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); 29 30 // 增加对AspectJ的支持 31 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { 32 beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); 33 beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); 34 } 35 36 // 注册默认的环境信息到一级缓存中 37 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { 38 beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); 39 } 40 // 注册系统属性到容器的一级缓存中 41 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { 42 beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); 43 } 44 // 注册系统环境到容器的一级缓存中 45 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { 46 beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); 47 } 48 }
1、设置beanFactory的类加载器;
2、设置beanFactory的表达式语言处理器; 3、设置beanFactory的属性编辑器; 4、完成BeanPostProcessor的注册,如ApplicationContextAwareProcessor、ApplicationListenerDetector; 5、设置忽略自动装配的接口,该部分接口有ioc容器通过set方法注入的; 6、设置自动装配的规则; 7、将环境信息注册到IOC容器中。