Spring源码分析 3:bean的实例化

    科技2022-07-14  111

    bean的实例化

    核心方法AbstractApplicationContext#refresh()1. invokeBeanFactoryPostProcessors(beanFactory);1.1 AbstractApplicationContext#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)1.2 PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List< BeanFactoryPostProcessor> beanFactoryPostProcessors) 2. registerBeanPostProcessors(beanFactory);2.1 AbstractApplicationContext#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)2.2 PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)2.3 PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List< BeanPostProcessor> postProcessors) 3. finishBeanFactoryInitialization(beanFactory);3.1 AbstractApplicationContext#finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)3.2 DefaultListableBeanFactory#preInstantiateSingletons()3.3 AbstractBeanFactory#getBean(String name)3.4 AbstractBeanFactory#doGetBean(final String name, @Nullable final Class requiredType,@Nullable final Object[] args, boolean typeCheckOnly)3.5 DefaultSingletonBeanRegistry#getSingleton(String beanName, ObjectFactory<?> singletonFactory)3.6 DefaultSingletonBeanRegistry#beforeSingletonCreation(String beanName)3.7 回到3.4步 doGetBean(),AbstractAutowireCapableBeanFactory#createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)3.8 AbstractAutowireCapableBeanFactory#doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)3.9 AbstractAutowireCapableBeanFactory#createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)3.10 AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)3.11 回到3.9步 createBeanInstance方法,AbstractAutowireCapableBeanFactory#autowireConstructor(beanName, mbd, ctors, args)3.12 回到3.9步 createBeanInstance方法,AbstractAutowireCapableBeanFactory#instantiateBean(beanName, mbd);3.13 回到3.8步doCreateBean(),AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);3.14 CommonAnnotationBeanPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)3.15 CommonAnnotationBeanPostProcessor#findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs)3.16 回到3.13步, AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)搜集过程总结3.17 回到3.8步doCreateBean(),AbstractAutowireCapableBeanFactory#populateBean(beanName, mbd, instanceWrapper);3.18 AutowiredAnnotationBeanPostProcessor#postProcessProperties(PropertyValues pvs, Object bean, String beanName)3.19 InjectionMetadata#inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs)3.20 AutowiredAnnotationBeanPostProcessor#inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs)3.21 回到3.8步doCreateBean()方法,AbstractAutowireCapableBeanFactory#initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)3.22 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)3.23 AbstractAutowireCapableBeanFactory#invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)initializeBean()内调用过程总结3.24 回到3.8步doCreateBean()方法,AbstractBeanFactory#registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) 总结

    核心方法AbstractApplicationContext#refresh()

    public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); /**重要程度:5 * 1、创建BeanFactory对象 * 2、xml解析 * 传统标签解析:bean、import等 * 自定义标签解析 如:<context:component-scan base-package="org.example"/> * 自定义标签解析流程: * a、根据当前解析标签的头信息找到对应的namespaceUri * b、加载spring所以jar中的spring.handlers文件。并建立映射关系 * c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类 * d、调用类的init方法,init方法是注册了各种自定义标签的解析类 * e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析 * 3、把解析出来的xml标签封装成BeanDefinition对象 */ // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); /* * BeanDefinitionRegistryPostProcessor * BeanFactoryPostProcessor * 完成对这两个接口的调用 * 1.spring启动过程中完成对beanDefinition对象的新增或修改 * 2.实现BeanDefinitionRegistryPostProcessor这个接口的类优先于其他类实例化 * */ // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); /* * 把实现了BeanPostProcessor接口的类实例化,并且加入到BeanFactory中 * */ // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); /* * 国际化,重要程度2 * */ // Initialize message source for this context. initMessageSource(); //初始化事件管理类 // Initialize event multicaster for this context. initApplicationEventMulticaster(); //这个方法着重理解模板设计模式,因为在springboot中,这个方法是用来做内嵌tomcat启动的 // Initialize other special beans in specific context subclasses. onRefresh(); //往事件管理类中注册事件类 // Check for listener beans and register them. registerListeners(); /* * 这个方法是spring中最重要的方法,没有之一 * 所以这个方法一定要理解要具体看 * 1、bean实例化过程 * 2、ioc * 3、注解支持 * 4、BeanPostProcessor的执行 * 5、Aop的入口 * * */ // 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(); } } }

    1. invokeBeanFactoryPostProcessors(beanFactory);

    完成对BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor这两个接口的调用。 1、spring启动过程中完成对beanDefinition对象的新增或修改; 2、实现BeanDefinitionRegistryPostProcessor这个接口的类优先于其他类实例化。

    1.1 AbstractApplicationContext#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)

    1.2 PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List< BeanFactoryPostProcessor> beanFactoryPostProcessors)

    这里调用getBean()方法就可以实例化bean,所以才能优先于其他类实例化。BeanDefinitionRegistryPostProcessor 这个接口的调用分为三步: 1、调用实现了 PriorityOrdered 排序接口 2、调用实现了 Ordered 排序接口 3、没有实现接口的调用这个接口的理解:获取 BeanDefinitionRegistry 对象,获取到这个对象就可以获取这个对象中注册的所有 BeanDefinition 对象,拥有这个对象就可以完成里面所有 BeanDefinition 对象的修改或新增操作。 public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); //获取实现了BeanDefinitionRegistryPostProcessor接口的所有类的BeanDefinition对象的beanName // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { //判断是否实现了排序接口 PriorityOrdered if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } //排序 sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); //调用实现BeanDefinitionRegistryPostProcessor接口的类的postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { //判断是否是实现的Ordered接口 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); //没实现排序接口的调用 // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. boolean reiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } //调用postProcessBeanFactory方法 // Now, invoke the postProcessBeanFactory callback of all processors handled so far. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } //获取实现了BeanFactoryPostProcessor接口的类,获取beanDefinition的名称 // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } //实现了PriorityOrdered接口的 else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } //实现了Ordered接口的 else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { //没实现接口的 nonOrderedPostProcessorNames.add(ppName); } } //排序 // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); //调用 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... beanFactory.clearMetadataCache(); }

    2. registerBeanPostProcessors(beanFactory);

    把实现了BeanPostProcessor接口的类实例化,并且加入到BeanFactory中(因为实现了BeanPostProcessor接口的类会优先实例化,所以要加入BeanFactory中)。

    2.1 AbstractApplicationContext#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)

    2.2 PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)

    public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { //拿到工程里面所有实现了BeanPostProcessor接口的类,获取到BeanDefinition的名称 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); //提前实例化BeanPostProcessor类型的bean,然后bean进行排序 for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { //getBean是实例化方法 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); //判断类型是否是MergedBeanDefinitionPostProcessor,如果是则代码是内部使用的 if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); //注册到BeanFactory中 registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }

    2.3 PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List< BeanPostProcessor> postProcessors)

    BeanPostProcessors注册到BeanFactory

    判断beanPostProcessor是不是InstantiationAwareBeanPostProcessor接口类型的,如果是就设置变量hasInstantiationAwareBeanPostProcessors=true,这个变量后面会用到;判断beanPostProcessor是不是DestructionAwareBeanPostProcessor接口类型的,如果是就设置变量hasDestructionAwareBeanPostProcessors=true;把beanPostProcessor添加到beanPostProcessors集合中(里面保存了所有的beanPostProcessor)

    3. finishBeanFactoryInitialization(beanFactory);

    1、bean实例化过程 2、ioc 3、注解支持 4、BeanPostProcessor的执行 5、Aop的入口

    3.1 AbstractApplicationContext#finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { //设置类型转换器 // Initialize conversion service for this context. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. //暂时不看 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } //暂时不看 // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes. beanFactory.freezeConfiguration(); //重点方法,重要程度:5 // Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); }

    3.2 DefaultListableBeanFactory#preInstantiateSingletons()

    具体实例化过程

    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. //xml解析时,把所有beanName都缓存到beanDefinitionNames了 List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : beanNames) { //父子BeanDefinition的合并,把父BeanDefinition里面的属性拿到子BeanDefinition中 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //如果不是抽象的,单例的,非懒加载的就实例化 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //判断bean是否实现了FactoryBean接口,这里可以不看 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); } } } else { //主要从这里进入,看看实例化过程 getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } }

    3.3 AbstractBeanFactory#getBean(String name)

    3.4 AbstractBeanFactory#doGetBean(final String name, @Nullable final Class requiredType,@Nullable final Object[] args, boolean typeCheckOnly)

    doGetBean要么从缓存中拿到对象,要么去createBean这个对象

    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType, @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); System.out.println("====beanName=="+beanName+"===instance begin===="); Object bean; //从缓存中拿实例 // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName); //如果缓存里面能拿到实例(如果是第一次进来肯定是没有实例的) if (sharedInstance != null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } //改方法是FactoryBean接口的调用入口 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { //如果singletonObjects缓存里面没有,则走下来 // Fail if we're already creating this bean instance: // We're assumably within a circular reference. //如果是scope 是Prototype的,校验是否有出现循环依赖,如果有则直接报错 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } //没有父容器,就不会进下面的if // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { //父子BeanDefinition合并 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); //获取依赖对象属性,依赖对象要先实例化,查看depends-on属性 // Guarantee initialization of beans that the current bean depends on. 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 { //实例化 getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } //着重看,大部分是单例的情况 // Create bean instance. if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); //改方法是FactoryBean接口的调用入口 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } //改方法是FactoryBean接口的调用入口 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); //改方法是FactoryBean接口的调用入口 bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // Check if required type matches the type of the actual bean instance. if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isTraceEnabled()) { logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }

    3.5 DefaultSingletonBeanRegistry#getSingleton(String beanName, ObjectFactory<?> singletonFactory)

    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "Bean name must not be null"); synchronized (this.singletonObjects) { //如果缓存中有,则直接返回 Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); } //把beanName添加到singletonsCurrentlyInCreation Set容器中,在这个集合里面的bean都是正在实例化的bean beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try { //如果这里有返回值,就代表这个bean已经结束创建了,已经完全创建成功 singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } //bean创建完成后singletonsCurrentlyInCreation要删除该bean afterSingletonCreation(beanName); } if (newSingleton) { System.out.println("====beanName==" + beanName + "===instance end===="); //创建对象成功时,把对象缓存到singletonObjects缓存中,bean创建完成时放入一级缓存 addSingleton(beanName, singletonObject); } } return singletonObject; } }

    3.6 DefaultSingletonBeanRegistry#beforeSingletonCreation(String beanName)

    把这个beanName放到singletonsCurrentlyInCreationSet容器中,在这个集合里面的 bean 都是正在实例化的 bean,就是实例化还没做完的 BeanName

    3.7 回到3.4步 doGetBean(),AbstractAutowireCapableBeanFactory#createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { if (logger.isTraceEnabled()) { logger.trace("Creating instance of bean '" + beanName + "'"); } 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. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { /* * TargetSource接口的运用,可以在用改一个类实现该接口,然后在里面定义实例化对象的方式,然后返回 * 也就是说不需要spring帮助我们实例化对象 * 这里可以直接返回实例本身 * */ // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { //主要看这个方法,重要程度 5 Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isTraceEnabled()) { logger.trace("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } }

    3.8 AbstractAutowireCapableBeanFactory#doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)

    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //创建实例,,重点看,重要程度:5 instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = instanceWrapper.getWrappedInstance(); Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { //CommonAnnotationBeanPostProcessor 支持了@PostConstruct,@PreDestroy,@Resource注解 //AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解 //BeanPostProcessor接口的典型运用,这里要理解这个接口 //对类中注解的装配过程 //重要程度5,必须看 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. //是否 单例bean提前暴露 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } //这里着重理解,对理解循环依赖帮助非常大,重要程度 5 添加三级缓存 addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; try { //ioc di,依赖注入的核心方法,该方法必须看,重要程度:5 populateBean(beanName, mbd, instanceWrapper); //bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5 exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { //注册bean销毁时的类DisposableBeanAdapter registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }

    3.9 AbstractAutowireCapableBeanFactory#createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)

    实例化方法,把 bean 实例化,并且包装成 BeanWrapper如果有FactoryMethodName属性,通过instantiateUsingFactoryMethod这个方法,反射得到实例化对象,并交给spring容器管理@Bean的实现原理也是通过spring 扫描有@bean 注解的方法,然后把方法名称设置到 BeanDefinition 的 factoryMethod 属性中,接下来就会调到instantiateUsingFactoryMethod方法实现@Bean 方法的调用

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Make sure bean class is actually resolved at this point. //反射拿到Class对象 Class<?> beanClass = resolveBeanClass(mbd, beanName); if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } //如果有FactoryMethodName属性 if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... boolean resolved = false; boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) { return autowireConstructor(beanName, mbd, null, null); } else { return instantiateBean(beanName, mbd); } } // Candidate constructors for autowiring? //寻找当前正在实例化的bean中有@Autowired注解的构造函数 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { //如果ctors不为空,就说明构造函数上有@Autowired注解 return autowireConstructor(beanName, mbd, ctors, args); } // Preferred constructors for default construction? ctors = mbd.getPreferredConstructors(); if (ctors != null) { return autowireConstructor(beanName, mbd, ctors, null); } //无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化 // No special handling: simply use no-arg constructor. return instantiateBean(beanName, mbd); }

    通过方法对象invoke,传入实例对象和入参

    3.10 AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)

    寻找当前正在实例化的bean中有@Autowired注解的构造函数有参构造函数的时候,determineConstructorsFromBeanPostProcessors这个方法是 BeanPostProcessor 接口类的首次应用,最终会调到 AutowiredAnnotationBeanPostProcessor 类的方法,在方法中会扫描有注解的构造函数然后完成装配过程。然后把有@Autowired 注解的构造函数返回。

    protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) throws BeansException { if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) { //拿到所有的实现了BeanPostProcessor的类并循环 for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; //找到类中有Autowired注解的构造函数 Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors != null) { return ctors; } } } } return null; } 只有AutowiredAnnotationBeanPostProcessor这个类中的determineCandidateConstructors方法有具体实现,用来找到类中有Autowired注解的构造函数,其他几个类的determineCandidateConstructors方法都是空方法(因为其他的类并不关心构造函数上是否有注解)

    获取到构造函数上的@Autowired注解信息

    3.11 回到3.9步 createBeanInstance方法,AbstractAutowireCapableBeanFactory#autowireConstructor(beanName, mbd, ctors, args)

    有@Autowired注解的有参构造函数,如果函数是一个引用类型,就会触发这个引用类型的getBean操作例如下面这种有@Autowired注解的构造函数

    3.12 回到3.9步 createBeanInstance方法,AbstractAutowireCapableBeanFactory#instantiateBean(beanName, mbd);

    无参构造函数的实例化包装成BeanWrapper对象并返回

    3.13 回到3.8步doCreateBean(),AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

    实例化完成后接下来就需要对类中的属性进行依赖注入操作,但是类里面属性和方法的依赖注入是用@Autowired 或者@Resource 注解完成的CommonAnnotationBeanPostProcessor 支持了@PostConstruct,@PreDestroy,@Resource注解AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解这是一个搜集过程,为了ioc依赖注入,搜集完注解才知道要依赖注入什么东西

    3.14 CommonAnnotationBeanPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)

    1、扫描类里面的属性或者方法 2、判断属性或者方法上面是否有@PostConstruct @PreDestroy @Resource注解 3、如果有注解的属性或者方法,包装成一个类

    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { //扫描@PostConstruct @PreDestroy,并放到checkedInitMethods和checkedDestroyMethods容器中 super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName); //扫描@Resource,扫描属性和方法上面是否有@Resource注解,如果有则收集起来封装成对象 InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); } CommonAnnotationBeanPostProcessor类的构造方法,对@PostConstruct和@PreDestroy注解的搜集

    这两种注解只能作用在方法(method)上

    3.15 CommonAnnotationBeanPostProcessor#findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs)

    1、看缓存里面有没有 InjectionMetadata 对象 2、 如果没有就到类中去搜集注解@Resource,如果有注解封装成 ResourceElement 对象 3、最终把包含属性和方法的对象Member(field和method的顶层父类)封装到 InjectedElement对象中,再把InjectedElement封装到InjectionMetadata对象中,缓存到Map中并返回

    3.16 回到3.13步, AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)

    对@Autowired 注解的属性和方法的收集。收集过程基本上跟@Resource 注解的收集差不多,同样包装成InjectionMetadata对象,缓存daoMap中并返回。

    搜集过程总结

    首先走到一个beanpostprocessor,如果是CommonAnnotationBeanPostProcessor,拿到正在实例化的bean的反射对象,再拿到这个对象里面的所有属性和方法,循环这些属性和方法,判断是否有对应的注解(@PostConstruct,@PreDestroy,@Resource),如果有就包装成InjectedElement对象,放入集合,再包装成InjectionMetadata对象

    3.17 回到3.8步doCreateBean(),AbstractAutowireCapableBeanFactory#populateBean(beanName, mbd, instanceWrapper);

    ioc di,依赖注入的核心方法

    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { if (bw == null) { if (mbd.hasPropertyValues()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. boolean continueWithPropertyPopulation = true; //这里实现接口可以让所有类都不能依赖注入 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { //是否需要DI,依赖注入 continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null; //重点看这个if代码块,重要程度 5 if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //依赖注入过程,@Autowired的支持 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } //老版本用这个完成依赖注入过程,@Autowired的支持 pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; } } } if (needsDepCheck) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } checkDependencies(beanName, mbd, filteredPds, pvs); } //这个方法建议不看,是老版本用<property name="username" value="fisher"/> //标签做依赖注入的代码实现,复杂且无用 if (pvs != null) { applyPropertyValues(beanName, mbd, bw, pvs); } }

    3.18 AutowiredAnnotationBeanPostProcessor#postProcessProperties(PropertyValues pvs, Object bean, String beanName)

    前面已经对@Resource@Autowired 注解进行了收集,这个方法就是根据收集到的注解进行反射调 用

    注入方法

    //从缓存中拿到InjectionMetadata对象 InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { //属性和方法的注入 metadata.inject(bean, beanName, pvs); }

    3.19 InjectionMetadata#inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs)

    循环收集到的 metaData 中集合里的对象,然后调用里面的 InjectedElement 的 inject 方法完成依赖注入

    3.20 AutowiredAnnotationBeanPostProcessor#inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs)

    和3.11的有参构造函数实例化一样,beanFactory.resolveDependency()最后会调到beanFactory.getBean(beanName)方法,从 spring 容器中获取到需要注入的实例,赋值给value。

    把value作为属性field,赋给正在实例化的bean

    MyAnnotationClass类正在实例化,通过@Autowired注解,把Student类作为属性注入到MyAnnotationClass中

    如果是通过有参构造方法注入

    members强转成method

    arguments得到需要注入的构造方法

    有参构造方法作为方法注入给正在实例化的bean

    java反射,method.invoke(),field.set()

    基于注解的ioc依赖注入完成基于xml配置的依赖注入在第3.17步,populateBean()方法中,建议不看,是老版本用< property name=“username” value=“Jack”/>标签做依赖注入的代码实现,很复杂,专门做 xml 配置依赖注入的,基本上现在基于 xml 配置的依赖很少使用。

    3.21 回到3.8步doCreateBean()方法,AbstractAutowireCapableBeanFactory#initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)

    在bean实例化和ioc依赖注入完以后的,一些方法的调用首先是对某些 Aware 接口的调用;然后@PostConstruct 注解方法的调用;InitializingBean 接口调用,实现了 InitializingBean 接口的类就必然会调用到 afterPropertiesSet;init-method 属性调用,Init-method 属性调用是在 afterPropertiesSet 之后;afterPropertiesSet和Init-method和有@PostConstruct注解的方法核心功能都是一样的,只是调用时序不一样而已,都是在该类实例化和 IOC 做完后调用的,我们可以在这些方法中做一些在 spring 或者 servlet 容器启动的时候的初始化工作。比如缓存预热,比如缓存数据加载到内存,比如配置解析,等等初始化工作。

    protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { //调用Aware方法 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //对类中某些特殊方法的调用,比如@PostConstruct,Aware接口,非常重要 重要程度 :5 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { //InitializingBean接口,afterPropertiesSet,init-method属性调用,非常重要,重要程度:5 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }

    3.22 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)

    @PostConstruct 注解方法的调用

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; /* * 1、ApplicationContextAwareProcessor类,对某个Aware接口方法的调用 * 2、InitDestroyAnnotationBeanPostProcessor类,@PostConstruct注解方法的调用 * 3、ImportAwareBeanPostProcessor类,对ImportAware类型实例setImportMetadata调用 * */ for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; } CommonAnnotationBeanPostProcessor继承了InitDestroyAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor之前已经对@PostConstruct注解进行了搜集,所以这里进入InitDestroyAnnotationBeanPostProcessor调用@PostConstruct注解的方法

    java反射调用

    3.23 AbstractAutowireCapableBeanFactory#invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)

    InitializingBean接口的afterPropertiesSet方法调用

    init-method属性调用

    在mybatis里的xml解析就是使用InitializingBean接口的afterPropertiesSet方法,在bean实例化完成以后,调用afterPropertiesSet方法。

    initializeBean()内调用过程总结

    1、BeanNameAware接口,2、@PostConstruct,3、afterPropertiesSet(),4、init-Method属性

    代码示例

    测试类实现 InitializingBean和BeanNameAware接口,重写afterPropertiesSet和setBeanName方法,添加了@PostConstruct注解,又写了一个initMethod方法(使用< bean>设置init-method属性)

    查看打印

    @PostConstruct,InitializingBean接口,init-Method属性的作用是一样的,都是为了在bean实例化完成后做一些工作对应的,在bean销毁前要做一些工作使用 @PreDestroy、DisposableBean接口、destory-method属性

    3.24 回到3.8步doCreateBean()方法,AbstractBeanFactory#registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd)

    销毁方法

    这个DisposableBeanAdapter对象就是负责bean销毁的类。在这个类中收集了该bean 是否实现了 DisposableBean 接口,是否配置 destroy-method 属性,过滤了 DestructionAwareBeanPostProcessor 类型的接口。

    在 tomcat 关闭的时候就会调用到 servlet 中的销毁方法

    总结

    1.invokeBeanFactoryPostProcessors完成对BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor这两个接口的调用

    获取beanFactory中所有实现了BeanDefinitionRegistryPostProcessor接口的类的beanName遍历这些beanName,分成实现PriorityOrdered、Ordered、没实现排序接口的三种实现类分别对这三类实现类进行排序,然后调用postProcessBeanDefinitionRegistry(如果没有使用spring.xml配置自定义标签解析,而是使用注解@ComponentScan(“com.example.demo”),那么此步中会调用ComponentScanAnnotationParser的parse方法创建注解扫描scaner),可以对beanDefinition的添加和修改

    2.registerBeanPostProcessors把实现了BeanPostProcessor接口的类实例化,并且加入到BeanFactory中

    拿到所有实现了BeanPostProcessor接口的类,判断接口类型,添加到beanPostProcessors集合中

    3.finishBeanFactoryInitialization bean实例化过程,ioc,注解支持

    如果不是抽象的,单例的,非懒加载的就实例化getBean(beanName)要么从缓存中拿到对象,要么去createBean这个对象,包括对父子BeanDefinition合并getSingleton如果缓存中有,则直接返回;如果没有,就把beanName添加到singletonsCurrentlyInCreation的Set容器中,在这个集合里面的bean都是正在实例化的bean,bean创建完成后singletonsCurrentlyInCreation要删除该bean;开始调用createBean方法创建对象,如果创建对象成功,把对象从singletonsCurrentlyInCreation中删除,然后缓存到singletonObjects一级缓存中

    3.1、createBean

    createBeanInstance-创建实例,通过推断出来的构造方法反射实例化对象,包装成BeanWrapper对象并返回

    applyMergedBeanDefinitionPostProcessors-对类中注解的装配过程,扫描bean里面的属性或者方法,判断属性或者方法上面是否有@PostConstruct @PreDestroy @Resource @Autowired注解,如果有就包装成InjectionMetadata对象放入缓存,完成对注解的收集

    addSingletonFactory-循环依赖,添加三级缓存

    populateBean-依赖注入的核心方法,postProcessProperties()从缓存中拿到InjectionMetadata对象,使用inject方法,如果是把类作为属性注入就getBean,把Bean作为属性注入,如果是构造方法注入,就反射调用完成依赖注入,把有@Autowired注解的方法或属性注入到正在实例化的Bean中

    initializeBean-实例化+ioc依赖注入完以后的调用,比如@PostConstruct注解方法的反射调用

    registerDisposableBeanIfNecessary-负责bean销毁

    Processed: 0.015, SQL: 8