Spring源码解析
2020-11-25 13:49:37 0 举报
spring源码解析
作者其他创作
大纲/内容
初始化
isExternallyManagedInitMethod
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);bean对象描述放入集合中
beanInstance =span style=\"font-size: inherit;\
beforeSingletonCreation(beanName);记录当前对象的加载状态(正在创建中)singletonsCurrentlyInCreation 集合
PostProcessor后置处理器
1、如果发生循环依赖的对象,不需要代理的话,只需要二级缓存就可可以解决问题2、如果对象需要代理,二级缓存解决不了问题,需要三级缓存来解决问题
AspectJExpressionPointcut.matches();匹配表达式
Ab
autowireConstructor()选择构造器,如果构造器有参数,需要提前实例化构造器的参数对象AOPAspectJPointcutAdvisor构造器包含AbstractAspectJAdvice对象AbstractAspectJAdvice子类包含Method、AspectJExpressionPointcut、AspectInstanceFactory对象
prototype
AbstractXmlApplicationContext
@PostConstruct、@PreDestroy
if (isPrototypeCurrentlyInCreation(beanName)) 如果是单例解决循环依赖,如果不是直接抛出异常
k:av:ObjectFactory
Spring Bean
canApply
if (mbd.isSingleton()) { sharedInstance = font color=\"#ff0000\
shouldSkip();BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans#getBean实例化-有参数构造,创建对象->构造方法参数对象,提前实例化- >AspectjPointcutAdvisorspan style=\"font-size: inherit;\
Bean信息定义xmlpropertiesyaml
mm2
springBoot启动流程->通过import解析加载1、@SpringBootApplication2、@EnableAutoConfiguration3、@AutoConfigurationPackage @Import(AutoConfigurationPackages.Registrar.class)4、@Import(AutoConfigurationImportSelector.class)5、AutoConfigurationImportSelector->getCandidateConfigurations\\6、getSpringFactoriesLoaderFactoryClass()->EnableAutoConfiguration.class7、org\\springframework\\boot\\spring-boot-autoconfigure\\META-INF\\spring.factories
在实现类中调用super.addBeanFactoryPostProcessor();
BeanFactory
4
IOC容器
封装对象BeanDefinition
MethodMatcher->matches
Ba
1、BeanNameAware2、BeanFactoryAware3、BeanClassLoaderAware
markBeanAsCreated(beanName);设置bean创建的标志alreadyCreated set集合已经创建的对象mergedBeanDefinitions 清除创建对象的定义信息
修改BeanDefinition信息
BeanPostProcessorafter
DefaultListableBeanFactory
BeanFactoryPostProcessor 接口PropertyOverrideConfigurer 抽象类PlaceholderConfigurerSupport 抽象类
AUTOWIRE_NO不注入AUTOWIRE_BY_NAME名称注入AUTOWIRE_BY_TYPE类型注入AUTOWIRE_CONSTRUCTOR构造器注入
BeanPostProcessorbefore
基本属性直接完成赋值操作
afterSingletonCreation(beanName);删除缓存中bean创建的标志
ApplicationContext context = new ClassPathXmlApplicationContext(\"applicationContext.xml\");context.getBean(\"xxx\");
1 super(parent);//调用父类构造器,相关对象创建,属性赋值2 public AbstractApplicationContext(@Nullable ApplicationContext parent) { this(); setParent(parent);//spring没有父子容器,springmvc中有 }2.1 AbstractApplicationContext 类 private String id = ObjectUtils.identityToString(this); 唯一标识2.2 private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>(); beanFactory后置处理器集合2.3 private final AtomicBoolean active = new AtomicBoolean(); private final AtomicBoolean closed = new AtomicBoolean(); 标志位2.4 private final Object startupShutdownMonitor = new Object(); 锁\"refresh\" and \"destroy\
PointcutAdvisor方法增强
initLifecycleProcessor();初始化LifecycleProcessor上下文中没有定义,则使用DefaultLifecycleProcessor
beanFactory.addPropertyEditorRegistrar 扩展1、定一个解析类继承PropertyEditorSupport2、重写setAsText(String text)3、自定义解析,setValue(object);4、定一个注册器类实现PropertyEditorRegistrar,加载自定义以解析类5、重写registerCustomEditors方法6、让Spring识别注册器,加载CustomEditorConfigurer, 设置PropertyEditorRegistrar[] propertyEditorRegistrars;
当完成实例化之后,要开始初始化赋值操作,赋值的类型有可能是引用类型,需要从spring容器中获取具体的对象来赋值,此时需要赋值的对象,如果被创建,直接获取对象,赋值;如果没有被创建,在整个过程中涉及到对象的创建过程,内部对象的创建又会有其他的依赖,其他的依赖在创建的过程中可能引用了当前对象,当前对象还没有创建完成,所以产生了循环依赖问题。
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();创建对象,扩展实现BeanFactoryPostProcessor,获取GenericBeanDefinition,设置setInstanceSupplier,函数式接口,调用get();回调具体方法
beanFactory.preInstantiateSingletons();实例化非懒加载的单例对现象
2
publishEvent(new ContextRefreshedEvent(this));创建新的ContextRefreshedEvent事件
BeanPostProcessor->postProcessAfterInitialization
如果对象的创建过程形成了闭环,那么就需要保证,该对象创建的过程不能有第二次,也就是说,在容器中获取该对象的时候必须获取到。对象的创建过程分为两步,实例化和初始化;实例化未完成初始化的对象可以给其他对象引用;此时需要把未完成初始化的对象暴露出去,让其他对象可以引用,就解决了闭环解环的问题。提前暴露对象的缓存集合(一级、二级、三级)singletonObjectsearlySingletonObjectssingletonFactories
AdviceExcludingMethodMatcher.matches()名称的匹配
K:ValueString:ObjectClass:ObjectString:ObjectFactoryString:BeanDefinition
Aware接口作用当Spring容器创建bean对象再进具体操作时,如果需要容器的其他对象,此时需要实现Aware接口,来满足需求
Spring 对象1.普通对象->自定义对象 BeanDefinition.ROLE_APPLICATION=0,BeanDefinition.SUPPORT=1 复杂的配置类2.容器对象->Spring容器内置对象 BeanDefinition.ROLE_INFRASTRUCTURE=2
AbstractBeanFacory
1、BeanPostProcessor 2、DestructionAwareBeanPostProcessor3、MergedBeanDefinitionPostProcessor4、InstantitionAwareBeanPostProcessor4-1、SmartInstantitionAwareBeanPostPorcessor
finishRefresh();完成刷新
BeanFactory实现应该支持标准的Bean生命周期接口,全套初始化方法及其标准顺序为:1.Aware BeanNameAware's BeanClassLoaderAware's BeanFactoryAware's EnvironmentAware's EmbeddedValueResolverAware's ResourceLoaderAware's ApplicationEventPublisherAware's MessageSourceAware's ApplicationContextAware's ServletContextAware's2.BeanPostProcessors postProcessBeforeInitialization3.InitializingBean's init-method4.BeanPostProcessors postProcessAfterInitialization
this.registeredSingletons.add(beanName);将完成对象名称,注册到有序的集合中
populate
BeanFactoryPostProcessor
beanFactory.addEmbeddedValueResolver();设置值解析器,没有设置默认的例子PlaceholderConfigurerSupport
ClassPathXmlApplicationContext(\"applicationContext.xml\");
AbstractRefreshableWebApplicationContext
ClassPathXmlApplicationContext
k:av:A@6666
mm1
DI依赖注入
1.PropertiesBeanDefinitionReader2.GroovyBeanDefinitionReader3.XmlBeanDefinitionReader
AOP是否需要创建代理对象
1.beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); 设置是否允许相同名称的不同定义bean覆盖2.beanFactory.setAllowCircularReferences(this.allowCircularReferences); 设置是否允许bean之间的自动循环引用
1、实现了InitializingBean接口调用 afterPropertiesSet方法2、用户自定义的初始化方法 invokeCustomInitMethod
k:bv:ObjectFactory
init-method
1、Aspect 切面2、Advisor->Advice 通知3、Pointcut 切点
ConfigurableBeanFactory
AbstractAutowireCapableBeanFactory
ExposeInvocationInterceptor.currentInvocation();ThreadLocal<MethodInvocation>方便后续获取
request
1.new StandardEnvironment(); 创建环境对象2.AbstractEnvironment()->customizePropertySources(this.propertySources); 定制化属性资源3.StandardEnvironment->customizePropertySources(MutablePropertySources propertySources); 子类实现
接口关系1.BeanFactory 根接口1.1.HierarchicalBeanFactory 父子(分层)容器接口1.1.1.ConfigurableBeanFactory 大多数bean工厂实现的配置接口1.2ListableBeanFactory 枚举所有bean对象1.3DefaultListableBeanFactory
ConfigBeanDefinitionParser#parseAspectJPointcutAdvisor-> AspectJMethodBeforeAdvice.class/ AspectJAfterAdvice.class/ AspectJAfterReturningAdvice.class/ AspectJAfterThrowingAdvice.class/ AspectJAroundAdvice.class -> MethodLocatingFactoryBean.class,font color=\"#ff0080\
Object singletonObject = this.singletonObjects.get(beanName);一级缓存获取
Spring创建Bean的几种方式1、doCreateBean 反射创建2、实现BeanPostProcessor接口,生成代理对象cglib InstantiationAwareBeanPostProcessor3、FactoryBean 接口规范,函数式接口,getObject()4、FactoryMethod 配置文件 factory-bean 实例工厂,factory-method静态工厂5、supplier AbstractBeanDefinition属性值,函数式接口,get()
加载xml
prepareRefresh();容器刷新准备工作
findEligibleAdvisors匹配符合条件的advisor
A@6666B@8888
当使用Spring的AOP创建N多个对象时,在创建过程中需要进行很多判断,判断当前对象是否需要代理,而代理之前,需要提前创建Advisor对象【resolveBeforeInstantiation】,才能进行后续的判断
createProxy();创建代理
Object sharedInstance = getSingleton(beanName);singletonObjects、earlySingletonObjects 、singletonFactories 三级缓存
clearResourceCaches();清除缓存资源
HierarchicalBeanFactory
实例化
静态代理代理类只能实现对”特定接口的实现类“进行代理
@PostConstruct
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\"); }font color=\"#ff3333\
5
isInfrastructureClass(bean.getClass());shouldSkip(); 不可以跳过【不是基础类,长度不包含.ORIGINAL】
resetCommonCaches();清楚缓存
@Resource
scope
LiveBeansView.registerApplicationContext(this);注册应用程序
增强Bean信息
1.constructorToUse = clazz.getDeclaredConstructor(); 获取构造器2.BeanUtils.instantiateClass(constructorToUse); 使用指定的构造器创建对象3.ctor.newInstance(args); 创建对象,内存开辟空间,属性赋默认值null
AbstractApplicationContext
postProcessAfterInitialization->wrapIfNecessary();创建动态代理
1
DynamicAdvisedInterceptorStaticUnadvisedExposedInterceptorSerializableNoOpStaticDispatcherAdvisedDispatcherEqualsInterceptorHashCodeInterceptor
实例化堆中开辟空间属性设置默认值
super(parent);调用父类构造器创建对象setConfigLocations(configLocations);设置配置文件路径refresh();核心方法
Map结构
PartialOrder.sort()topo-sort拓扑排序
填充信息
byte、short、int、long、float、double、boolean、char
instanceWrapper.getWrappedInstance();instanceWrapper.getWrappedClass();获取bean对象,获取class
BeanDefinition
AOP创建代理对象
1、ApplicationContextAwareProcessor2、InitDestroyAnnotationBeanPostProcessor3、CommonAnnotationBeanPostProcessor4、AutowiredAnnotationBeanPostProcessor
spring
调用getBeanAbstractAutoProxyCreator#postProcessBeforeInstantiation如果是基础类【Advice.class、Pointcut.class、Advisor.class、AopInfrastructureBean.class】加入缓存【advisedBeans】,标记为fasle
AbstractAdvisorAutoProxyCreator->getAdvicesAndAdvisorsForBean返回排序后的Advisor
singletonObject = singletonFactory.getObject();调用匿名内部类createBean方法
实现了BeanDefinitionRegistryPostProcessor
beanFactory.freezeConfiguration();缓存不需要修改的beanDefinition信息
数组ListMapSetProperties
Boolean.FALSE.equals(this.advisedBeans.get(cacheKey));跳过
1 setConfigLocations(configLocations);//资源路径占位符替换2 protected String resolvePath(String path) { return getEnvironment().resolveRequiredPlaceholders(path); }3 protected ConfigurableEnvironment createEnvironment() { return new StandardEnvironment(); }4 AbstractEnvironment 父类初始化4.1 public static final String IGNORE_GETENV_PROPERTY_NAME = \"spring.getenv.ignore\";4.2 public static final String ACTIVE_PROFILES_PROPERTY_NAME = \"spring.profiles.active\";4.3 public static final String DEFAULT_PROFILES_PROPERTY_NAME = \"spring.profiles.default\
类型转换
解析xml
引用类型容器中获取对象有直接赋值,没有创建对象
类型匹配
loadBeanDefinitions(beanFactory);加载配置BeanDefinition信息到当前工厂中doLoadBeanDefinitions();执行doLoadBeanDefinitions加载配置自定义信息
动态代理代理类可以实现对多种类的代理
方法参数
singletonFactories
BeanFactory与FactoryBean区别?1.都可以用来创建对象;2.BeanFactory创建对象,要遵守完成的创建过程,由Spring管理规范;3.FactoryBean创建对象调用getObject()方法,这个过程由用户来控制比较灵活;
bean对象
this.earlySingletonObjects.remove(beanName);删除二级缓存
BeanFactory 和FactoryBean1、都是对象工厂,都可以创建对象2、如果使用BeanFactory,那么要个遵守spring创建对象的生命周期 实例化:Aware-> BeanPostProcessors postProcessBeforeInitialization-> InitializingBean's init-method -> BeanPostProcessors postProcessAfterInitialization-> destroy-method3、FactoryBean不需要遵守spring创建流程 getObjectType FactoryBean创建的对象类型 isSingleton 是不是单例对象 getObject 返回对象的实例 【new Object()】4、FactoryBean创建两个对象,被Spring管理 子类对象,对象存储span style=\"font-size: inherit;\
earlySingletonObjects
set方式注入分类
factory.getObject();返回具体对象
getLifecycleProcessor().onRefresh();刷新生命周期接口
beanFactory.setConversionService();设置类型转换“conversionService”可以设置自定义转换器
AOP
final String beanName = transformedBeanName(name);获取对应的beanNamebean对象如果实现FactoryBean后会变成font color=\"#ff0000\
singletonObjects
sortAdvisors(eligibleAdvisors);
BeanDefinitionReader 接口AbstractBeanDefinitionReader 抽象类GroovyBeanDefinitionReaderPropertiBeanDefinitionReaderXmlBeanDefinitionReader
用户手动添加的实现了BeanFactoryPostProcessor
1.postProcessBeanFactory(beanFactory); BeanFactoryPostProcessor增强器,扩展实现2.invokeBeanFactoryPostProcessors(beanFactory); 实例化并执行所有的BeanFactoryPostProcessor 单例对象再实例化之前必须调用
AnnotationConfigWebApplicationContext
3
beanDefinitionReader.setEnvironment(getEnvironment());beanDefinitionReader.setResourceLoader(this);设置实体解析器,根据xsd/dtd规则解析对应的标签对象 beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));this.schemaResolver = new PluggableSchemaResolver(classLoader);DEFAULT_SCHEMA_MAPPINGS_LOCATION = \"META-INF/spring.schemas\"
invokeAwareMethods
BeanWrapper bw = new BeanWrapperImpl(beanInstance);为给定对象创建一个新的BeanWrapper(包装类)registerDefaultEditors(); 激活编辑器标识,允许在需要时注册编辑器initBeanWrapper(bw); 根据指定的BeanWrapper初始化bw.setConversionService(getConversionService());设置转换器registerCustomEditors(bw);注册自定义编辑器
@Autowired
extendAdvisors(eligibleAdvisors);
Aware忽略处理位置1、obtainFreshBeanFactory2、refreshBeanFactory3、createBeanFactory()4、DefaultListableBeanFactory()5、AbstractAutowireCapableBeanFactory()
AbstractAutoProxyCreator
完整对象cxt.getBean()
k:bv:B@8888
super
findCandidateAdvisors
ApplicationContext
IntroductionAdvisor类增加
cglib动态代理代理任意一个目标类,但对final类和方法无法代理MethodInterceptor 接口Enhancer enhancer = new Enhancer();enhancer.setSuperclass(objectTarget.getClass());enhancer.setCallback(this);Object proxyObj = enhancer.create(); 代理对象
setConfigLocations
IOC控制翻转
findAdvisorsThatCanApply对切面定义是否应用到当前bean
1.setBeanClassLoader(getClassLoader()); 设置类加载器 Thread.currentThread().getContextClassLoader(); 默认加载器2.beanFactory.setBeanExpressionResolver(); 为beanFactory设置解表达式解析器3.beanFactory.addPropertyEditorRegistrar(); 所有beanFactory创建时设置属性解析器4.beanFactory.addBeanPostProcessor( new ApplicationContextAwareProcessor(this)); 设置beanFacitory应用上下文callback5.beanFactory.ignoreDependencyInterface(); 忽略自动装配setter方法的依赖接口6.beanFactory.registerResolvableDependency(); 自动装配的特殊规则,ioc进行初始化有多个实现,使用指定的注入7.beanFactory.addBeanPostProcessor( new ApplicationListenerDetector(this)); 设置监听器检测内部bean8.beanFactory.registerSingleton(); 注册默认环境对象【getEnvironment()】
postProcessBeforeInitializationEnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware
增强BeanDefinition信息
refreshBeanFactory();子类刷新bean工厂
finishBeanFactoryInitialization(beanFactory);实例化所有的非懒加载的单例对象
ReflectionUtils.clearCache();AnnotationUtils.clearCache();ResolvableType.clearCache();CachedIntrospectionResults.clearClassLoader(getClassLoader());
singleton
BeanPostProcessor->postProcessBeforeInitialization
AbstractRefreshableApplicationContextAbstractRefreshableConfigApplicationContext
init-method只能用一次在InItDestroyAnnotationBeanPostProcessor中postProcessMergedBeanDefinition方法中的checkConfigMembers方法registerExternallyManagedInitMethod注册信息externallyManagedInitMethods集合中添加初始化方法
xml文件<beans><bean id=“xxxx”>set 注入;构造器注入</bean></beans>
ConfigurableApplicationContext
this.singletonFactories.remove(beanName); 删除三级缓存
解析定义规范方便扩展
session
ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();创建容器对象 DefaultListableBeanFactory
getBeanFactory();获取bean工厂
BeanPostProcessor 接口AbstractAutoProxyCreator抽象类InstantiationAwareBeanPostProcessorAdapter抽象类
实现了BeanFactoryPostProcessor
1、DestructionAwareBeanPostProcessors.postProcessBeforeDestruction()2、DisposableBean.destroy();3、用户自定义的destroy-method 【@PreDestroy】
beanFactory.setSerializationId(getId());设置序列化id
BeanFactory Bean工厂 Spring Bean访问的根接口ListableBeanFactoryConfigurableBeanFactory 接口AbstractAutowireCapableBeanFactory 抽象类DefaultListableBeanFactory 实现类反射Class.forName();对象.getClass();类.Class()Constructor constroctor =clazz.getConstructor();constroctor.newInstence();
ClassFilter->matchesexecution(* com.xxx.service.impl..*.*(..))
设置Awre接口属性
收藏
收藏
0 条评论
下一页