如上图所示,Spring注解ApplicationContext通过配置类创建IOC容器。
public AnnotationConfigApplicationContext(Class<?>... componentClasses) { this(); register(componentClasses); refresh(); } @Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. //prepareRefresh();刷新前的预处理工作 // 1. initPropertySources:初始化一些设置,留给子类自定义个性化的属性设置方法 // 2. getEnvironment().validateRequiredProperties();检验属性是否合法 // 3. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);保存容器中的事件 prepareRefresh(); //获取新创建的bean工厂,里面的属性都是默认的,详见第2节 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //beanFactory的预处理工作 prepareBeanFactory(beanFactory); try { //子类通过重写这个方法在BeanFactory创建并预先准备完成以后做进一步的设置。 postProcessBeanFactory(beanFactory); /* ----------- 上述部分为beanFacotry的预准备工作 */ //在BeanFactory标准初始化之后执行的后置处理器。 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. //留给子类实现一些逻辑 onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }BeanFactory准备工作完成后进行的后置处理工作
子类通过重写这个方法来在BeanFactory创建并预准备完成,做进一步的设置执行BeanFactoryPostProcessor:
BeanFactoryPostProcessor:BeanFactory的后置处理器。在BeanFactory标准初始化之后执行。
两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
其中BeanDefinitionRegistryPostcessor时BeanFactoryPostProcessor的子接口。
具体执行BeanFactoryPostProcessor的方法:
获取所有的BeanDefinitionRegistryPostProcessor;首先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor。 postProcessor.postProcessBeanDefinitionRegistry(registry); 在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor; postProcessor.postProcessBeanDefinitionRegistry(registry); 最后执行没有实现任何接口或者时顺序接口的BeanDefinitionRegistryPostProcessor;执行完BeanDefinitionRegistryPostProcessor之后再执行BeanFactoryPostProcessor
获取所有的BeanFactoryPostProcessor。首先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、 postProcessor.postProcessBeanFactory() 再执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor、 postProcessor.postProcessBeanFactory() 最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors postProcessor.postProcessBeanDefinitionRegistry(registry)获取所有的BeanPostProcessor、其有很多子接口,DestructionAwareBeanPostProcessor、InstantiationAwareBeanPostProcessor、SmartInstantiationAwareBeanPostProcessor、MergedBeanDefinitionPostProcessor。
获取所有的BeanPostProcessor;后置处理器都可以通过PriorityOrdered、Ordered接口来指定优先级,
同BeanFactoryPostProcessor相同,首先注册PriorityOrdered接口的BeanFactoryPostProcessor,把每一个BeanPostProcessor,添加到BeanFactory中
beanFactory.addBeanPostProcessor(postProcessor);
再注册Ordered接口的BeanFactoryPostProcessor
最后注册,没有实现任何优先级接口的
最后注册internalPostProcessor
注册完PostProcessor之后,注册一个ApplicationListenerDetector,来Bean创建完成后检查是否是ApplicationListener。
初始化MessageSource组件(做国际化功能,消息绑定,消息解析)
protected void initMessageSource() { //获取BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //判断容器中是否有名字为MESSAGE_SOURCE_BEAN_NAME的组件 //如果有id为messageSource的,类型是MessageSource的组件,如果有赋值给messagesource的组件,如果没有,自己创建一个。 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; //把创建好的messagesource注册再容器中,以后获取国际化配置可以调用getMessage()的方法。 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }给容器中将所有项目里面的ApplicationListener注册进来
protected void registerListeners() { // Register statically specified listeners first. for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! //从容器中拿到所有的ApplicationListener组件 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); //将所有的监听器添加到事件派发器中 for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }初始化所有剩下的单实例bean
// Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); @Override public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. //获得所有beanName List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... //依次初始化和创建对象 for (String beanName : beanNames) { //获得bean的定义信息 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //如果bean是抽象的,是单实例的,不是懒加载的 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //判断是否是FactoryBean,是否是实现FactoryBean接口的Bean。 if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } //如果不是工厂bean,利用getBean(beanName)创建对象 else { getBean(beanName); } } } }getBean方法中有doGetBean方法,下面来介绍doGetBean方法
Object sharedInstance = getSingleton(beanName); //如果beanName已经被创建过了,那么getSingleton()方法就能够获取到该对象。 先获取缓存中保存的单实例Bean。如果能获取说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来) private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);singletonObjects中就是保存单实例bean的
如果缓存中拿不到该对象,就去获得BeanFactory。标记当前Bean已经被创建 if (!typeCheckOnly) { markBeanAsCreated(beanName); } 获取bean的定义信息 //获取bean的定义信息 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. //获取当前bean依赖的所有bean String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); try { //如果有当前bean依赖的所有bean,就会事先创建当前bean所依赖的所有bean。 getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } }创建当前bean所依赖的bean。
启动单实例bean的创建流程。createBean(beanName, mbd, args);
@Override protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. mbdToUse.prepareMethodOverrides(); // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. //让beanPostProcessor先拦截返回代理对象 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } Object beanInstance = doCreateBean(beanName, mbdToUse, args); return beanInstance; } }Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
@Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<?> targetType = determineTargetType(beanName, mbd); if (targetType != null) { //如果该方法有返回值,直接触发bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);方法 bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } return bean; }如果applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);没有返回代理对象。那么就会开始创建bean。
doCreateBean()
创建Bean实例:createBeanInstance(beanName,mbd,args);利用工厂方法或者对象的构造器创建出Bean实例。applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);populateBean(beanName, mbd, instanceWrapper);Bean属性赋值 遍历所有的后置处理器,拿到InstantiationAwareBeanPostProcessor执行postProcessAfterInstantiation()遍历所有的后置处理器,拿到InstantiationAwareBeanPostProcessor,执行postProcessPropertyValues()applyPropertyValues,为属性利用setter方法等进行赋值。 Bean初始化initializeBean 执行invokeAwareMethods().执行后置处理器初始化之前的方法applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);invokeInitMethods(beanName, wrappedBean, mbd);执行初始化之前的方法applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 注册Bean销毁方法addSingleton(beanName,singletonObject);
检查所有的Bean是否是SmartInitializingSingleton接口的,如果是,就执行afterSingletonsInstantion方法
IOC容器创建完成。
protected void finishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). clearResourceCaches(); // Initialize lifecycle processor for this context. initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. getLifecycleProcessor().onRefresh(); // Publish the final event. publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext(this); } initLifecycleProcessor();初始化和生命周期有关的后置处理器。getLifecycleProcessor().onRefresh();拿到前面定义的生命周期处理器。回调onRefresh()方法发布容器完成刷新事件Spring容器再启动的时候,会先保存所有注册进来的Bean的定义信息;
xml注册bean:注解注册bean:@Service,@Component,@BeanSpring容器会合适的时机创建这些Bean
用到这个bean的时候,利用getBean创建bean;创建好以后保存再容器中。统一创建剩下所有的bean的时候,finishBeanFactoryInitialization()后置处理器
每一个bean创建完成时,都会使用各种后置处理器,增强一个bean的功能。AutowiredAnnotationBeanPostProcessor :处理自动注入AnnotationAwareAspectJAutoProxyCreator:给Bean创建代理对象做AOP。