Spring源码 - 容器刷新

  • refresh
        XmlWebApplicationContext:负责xml配置文件解析
    
    • 获取、刷新BeanFactory(DefaultListableBeanFactory)
      • 获取BeanFactory
          new DefaultListableBeanFactory(getInternalParentBeanFactory());
      
          getInternalParentBeanFactory() {
              //Spring context getParent()=null
              //MVC context getParent()=sc.getAttribute("WebApplicationContext.root") 获取到Spring的context
              if (getParent() instanceof ConfigurableApplicationContext) {
                  return ((ConfigurableApplicationContext) getParent()).getBeanFactory();
              }
              return getParent();
          }
          
          public AbstractAutowireCapableBeanFactory(BeanFactory parentBeanFactory) {
          	this();
          	//设置父类BeanFactory
          	setParentBeanFactory(parentBeanFactory);
          }
          //每次都会new一个DefaultListableBeanFactory
          //MVC将Spring的context(BeanFactory)设置为自己的父类
      
      • 解析xml配置文件 封装BeanDefinition
        • 默认标签 import、alias、bean、beans
        • 自定义标签
          • 根据标签的namespaceUri(context、mvc、aop)获取 NamespaceHandler
            • 解析 META-INF/spring.handlers 配置 放入DefaultNamespaceHandlerResolver.handlerMappings
              通过=拆分获取 key、value
                //spring-webmvc
                http://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler
                //spring-context <context:component-scan base-package="org.springframework.xx.service"/> 
                http://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler
                //spring-aop <aop:aspectj-autoproxy proxy-target-class="true" />
                http://www.springframework.org/schema/aop=org.springframework.aop.config.AopNamespaceHandler
            
            • 通过 namespaceUri 获取 handlerMappings 的值 得到 NamespaceHandler 的实现类,执行init()方法,初始化自定义标签解析器,
              放入缓存 NamespaceHandlerSupport.parsers
                public class AopNamespaceHandler extends NamespaceHandlerSupport {
                	public void init() {
                        ...
                        //aop注解解析器 <aop:aspectj-autoproxy proxy-target-class="true" />
                		registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
                		...
                	}
                }
                public class TxNamespaceHandler extends NamespaceHandlerSupport {
                	@Override
                	public void init() {
                	    //事务注解解析器 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/>
                		registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
                		...
                	}
                }
                public class ContextNamespaceHandler extends NamespaceHandlerSupport {
                	@Override
                	public void init() {
                	    //properties配置文件解析器 <context:property-placeholder location="classpath*:/app*.properties"/>
                		registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
                		...
                		...
                		//bean扫描解析器 <context:component-scan base-package="org.springframework.xx.service"/> 
                		registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
                		...
                	}
                
                }
            
          • 根据标签的 localName(component-scan、annotation-driven) 从 NamespaceHandlerSupport.parsers 获取解析器; 解析器都实现 BeanDefinitionParser 接口的 parse() 方法,进行各自的标签解析
              findParserForElement(element, parserContext).parse(element, parserContext);
              
              private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
              	String localName = parserContext.getDelegate().getLocalName(element);
              	BeanDefinitionParser parser = this.parsers.get(localName);
              	...
              	return parser;
              }
          
    • 注册BeanPostProcessor(后置处理扩展方式)
      • 允许在Spring实例化Bean的过程中修改Bean的属性、方法等
         public interface BeanPostProcessor {
              //前置方法 在Bean初始化前调用
         	    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
              //后置方法 在Bean实例化完成后执行,进行aop、@Transcation增强器(Advisor)获取之后获取代理对象
         	    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; 
         }
         以及扩展子类
         public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
              //后置方法 在Bean初始化实例后调用,解析@Autowire等注入注解
         	    void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
         }
         
         public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
         
         	    Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
          
         	    boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
              //后置方法 
         	    PropertyValues postProcessPropertyValues(
         	    		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException;
         	}
      
    • 实例化Bean
          AbstractAutowireCapableBeanFactory.doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      
      • 创建实例
          //工厂方法创建 - bean配置获取实例的factory-method
          //构造器创建 - 根据参数、个数获取构造器
          instanceWrapper = createBeanInstance(beanName, mbd, args);
      
      • 执行后置方法 BeanPostProcessor.postProcessMergedBeanDefinition(…) 后置解析@Autowire @Value @Resource等注解放入缓存;封装 FieldCallback 接口,各 BeanPostProcessor 在处理注解查找时,各自实现 FieldCallback.doWith()方法
         applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
             
             //AbstractAutowireCapableBeanFactory 
             protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
             	for (BeanPostProcessor bp : getBeanPostProcessors()) {
             		if (bp instanceof MergedBeanDefinitionPostProcessor) {
             			MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
             			bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
             		}
             	}
             }
        
        • 解析 @Autowire、@Value --> AutowiredAnnotationBeanPostProcessor 封装成 InjectionMetadata
            //初始化指定解析的注解类 放入集合 autowiredAnnotationTypes(set)
            public AutowiredAnnotationBeanPostProcessor() {
            	this.autowiredAnnotationTypes.add(Autowired.class);
            	this.autowiredAnnotationTypes.add(Value.class);
            	...
            }
            //遍历当前创建bean的field 判断是否含有 autowiredAnnotationTypes 中的注解
            private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
                    ...
            	    ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
            	    	@Override
            	    	public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            	    	    //获取注解 @Autowired @Value 封装 AnnotationAttributes
            	    		AnnotationAttributes ann = findAutowiredAnnotation(field);
            	    		...
            	    	}
            	    });
            	    ...
            	return new InjectionMetadata(clazz, elements);
            }
            
            private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
            	if (ao.getAnnotations().length > 0) {
            		for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
            			AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
            			if (attributes != null) {
            				return attributes;
            			}
            		}
            	}
            	...
            }
            
        
        • 解析 @Resource --> CommonAnnotationBeanPostProcessor 封装成 ResourceElement
            //遍历当前创建bean的field 判断是否含有 Resource 注解
            private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
            		...
            		ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
            			@Override
            			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            			    ...
            				if (field.isAnnotationPresent(Resource.class)) {
            					...
            					if (!ignoredResourceTypes.contains(field.getType().getName())) {
            						currElements.add(new ResourceElement(field, field, null));
            					}
            				}
            			}
            		});
            		...
            	return new InjectionMetadata(clazz, elements);
            }
        
      • 填充属性
        • 解析xml中配置的autowire进行处理
        • 后置调用 InstantiationAwareBeanPostProcessor.postProcessPropertyValues(…) 处理注解注入
            // AbstractAutowireCapableBeanFactory
            protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
            	...
            	if (hasInstAwareBpps || needsDepCheck) {
            		PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            		if (hasInstAwareBpps) {
            			for (BeanPostProcessor bp : getBeanPostProcessors()) {
            				if (bp instanceof InstantiationAwareBeanPostProcessor) {
            					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            					pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
            					if (pvs == null) {
            						return;
            					}
            				}
            			}
            		}
            		...
            	}
                ...
            }
            
            public PropertyValues postProcessPropertyValues(
            		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
                //注解解析 缓存存在直接获取
            	InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
            	..
            	    //调用反射方法注入 
            		metadata.inject(bean, beanName, pvs);
            	...
            }
        
      • 调用初始化方法 init-method
        • 反射调用init()
        • 如果当前的bean实现了 InitializingBean 接口 则调用 InitializingBean.afterPropertiesSet()
            AbstractHandlerMethodMapping.afterPropertiesSet() 解析含有Controller或RequestMapping注解的bean(Spring Mvc初始化流程)
            初始化mappingRegistry(requestMapping)
            
            //AbstractHandlerMethodMapping
            @Override
            public void afterPropertiesSet() {
            	initHandlerMethods();
            }
            
            protected void initHandlerMethods() {
            	...
            	    for (String beanName : beanNames) {
            			//解析含有Controller或RequestMapping注解的handler bean 获取handlerMethods
            			if (beanType != null && isHandler(beanType)) {
            				detectHandlerMethods(beanName);
            			}
            		}
            	...
            }
            protected void detectHandlerMethods(final Object handler) {
            	...
            	Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
            			new MethodIntrospector.MetadataLookup<T>() {
            				@Override
            				public T inspect(Method method) {
            					try {
            						return getMappingForMethod(method, userType);
            					}
            					...
            				}
            			});
            	//mappingRegistry缓存初始化
            	for (Map.Entry<Method, T> entry : methods.entrySet()) {
            		Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
                    T mapping = entry.getValue();
            		registerHandlerMethod(handler, invocableMethod, mapping);
            	}
            }
            //RequestMappingHandlerMapping 
            private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
                //@RequestMapping注解查找 封装RequestMappingInfo
            	RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
            	RequestCondition<?> condition = (element instanceof Class ?
            			getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
                //获取RequestCondition,用来进行请求匹配,包括headers、param等信息
            	return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
            }
        
        • 执行后置方法 BeanPostProcessor.postProcessAfterInitialization(result, beanName) 后置进行aop、@Transcation增强器(Advisor)解析、获取代理对象
          • 查找 Advisors
          • 匹配 Advisors 与 使用了注解的bean
          • 获取代理对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值