IOC容器创建步骤
- 创建容器
- bean的扫描
- 容器初始化
- 获取bean
- 创建bean
时序图
创建容器
- 我们写一个容器的创建代码,借此可以看IOC的执行流程
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext=new AnnotationConfigApplicationContext("com.spring.bean");
}
- 查看AnnotationConfigApplicationContext的对象创建是怎么操作的
public AnnotationConfigApplicationContext(String... basePackages) {
this();//创建工厂组件
scan(basePackages);//扫描配置
refresh();//初始化容器
}
从上面可以看到在我们创建对象的时候,会调用三个方法.也算是初始化.
- this();//创建工厂组件
- scan(basePackages);//扫描配置
- refresh();//初始化容器
this();//调用this()创建工厂所需要的组件
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
scan(basePackages);扫描需要进行IOC容器管理的bean,并把配置信息注册到容器中
本身自己什么都没做,调用ClassPathBeanDefinitionScanner.scan()方法扫描bean配置信息
1.
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
2. 调用 ClassPathBeanDefinitionScanner类 scan()方法。
记录下bean配置信息的个数,然后调用当前类的doScan()方法去完成扫描工作。
public int scan(String... basePackages) {
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
//扫描bean
doScan(basePackages);
// Register annotation config processors, if necessary.
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
3.调用ClassPathBeanDefinitionScanner类doScan(basePackages);进行扫描注册工作
-调用findCandidateComponents()方法,根据@Component注解扫描到对应的bean配置信息
-解析bean的作用域、生成bean的名称、解析设置bean的默认属性lazy,init,destory方法。
-调用registerBeanDefinition()方法把bean的信息保存到容器中。
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
//扫描对应包下的Components注解资源,把资源文件放到BeanDefinition配置里
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
//解析bean的scope作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
//生成bean的名称
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
//设置bean的一些默认属性,lazy,init,destory方法等
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
//通过解析类设置bean的一些属性,lazy,Primary,DependsOn等
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
//soope 是否需要设置代理
//解决@Scope(value = WebApplicationContext.SCOPE_SESSION,proxyMode =ScopedProxyMode.INTERFACES)
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
//注册bean的配置信息到容器
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
4. 在doScan()方法里调用 findCandidateComponents(basePackage);扫描带有@Component注解的bean
- 根据@Component注解扫描到需要IOC容器管理的class;
- 把扫描到的class解析成Resource,最后包装成BeanDefinition 配置信息
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
//走这里
return scanCandidateComponents(basePackage);
}
}
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
//把扫描到的文件解析成Resource资源
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (Resource resource : resources) {
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
if (resource.isReadable()) {
try {
//读取文件资源的各项属性
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
//是否包含component注解
if (isCandidateComponent(metadataReader)) {
//把候选资源转换为BeanDefinition
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setResource(resource);
sbd.setSource(resource);
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Identified candidate component class: " + resource);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + resource);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not matching any filter: " + resource);
}
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not readable: " + resource);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
5. 把扫描出来的bean注册到容器,在doScan()方法里调用registerBeanDefinition()
registerBeanDefinition(definitionHolder, this.registry);
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
6.最终调用BeanDefinitionReaderUtils类的registerBeanDefinition()方法进行配置注册工作
- 解析bean的Id 和别名
- 调用BeanDefinitionRegistry.registerBeanDefinition()方法把 bean的配置信息保存到beanDefinitionMap中
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// 定义和设置bean的名称,同时根据名称把bean的配置信息保存到beanDefinitionMap中
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// 设置bean的别名,同时建立别名和真正的名称建立关系保存到aliasMap中
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
容器初始化
public AnnotationConfigApplicationContext(String… basePackages) {
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
初始化步骤
调用refresh();进行容器初始化工作
1、调用prepareRefresh 进行容器预处理工作(初始化容器参数、时间、环境变量)
2、得到bean工厂
3、设置工厂配置属性信息(类加载器、表达式解析器、自动装配、后置处理监听检测、设置环境变量处理的bean)
4、先后执行实现了BeanDefinitionRegistryPostProcessor,BefactoryPostProcessor接口对象的逻辑。
5、把实现了beanPostProcessor接口的类信息保存到容器。
6、初始化消息资源解析器
7、初始化事件监听器
8、获得注册监听器、派发容器初始化的事件
9、调用finishBeanFactoryInitialization(beanFactory); 来开始准备创建bean.
10、进行一些初始化完成后的操作,触发一些事件工作。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//1、容器预处理工作
prepareRefresh();
// 2、获取bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3、设置工厂配置属性信息
prepareBeanFactory(beanFactory);
try {
// 子类通过此方法在BeanFactory初始化完成之后做自定义的进一步设置
postProcessBeanFactory(beanFactory);
// 执行 BeanFactoryPostProcessor后置处理器逻辑
invokeBeanFactoryPostProcessors(beanFactory);
// 把实现了beanPostProcessor接口的类信息添加到容器
registerBeanPostProcessors(beanFactory);
// 初始化消息资源解析器
initMessageSource();
// 初始化事件监听器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//容器初始化扩展方法,交给子类实现
onRefresh();
// 获得注册监听器、派发容器初始化的事件
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 工厂信息初始化完成后,开始创建单例非懒加载的bean
finishBeanFactoryInitialization(beanFactory);
//进行一些初始化完成后的操作
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.在refresh()里调用prepareRefresh();进行容器预处理;
prepareRefresh();
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
//初始化容器的属性值,交给子类容器自己处理
initPropertySources();
//环境变量验证
getEnvironment().validateRequiredProperties();
//保存容器早期事件
this.earlyApplicationEvents = new LinkedHashSet<>();
}
2.在refresh()里 调用obtainFreshBeanFactory()获取bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//设置容器状态信息
refreshBeanFactory();
//获得beanFactory (构造方法已创建)
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
调用refreshBeanFactory()
protected final void refreshBeanFactory() throws BeansException {
//先清空已存在Beanfactory
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//创建beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//
beanFactory.setSerializationId(getId());
//定义工厂创建bean的规则
customizeBeanFactory(beanFactory);
//加载配置文件、把配置文件解析为beandefinishion
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
3.在refresh()方法里调用prepareBeanFactory()设置工厂的基础属性
prepareBeanFactory(beanFactory);
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//3.1、类加载器
beanFactory.setBeanClassLoader(getClassLoader());
//表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//忽略自动装配接口
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
//3.4、注册自动装配接口
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
//添加后置处理器事件监听检测
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
//注册环境变量相关bean
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
在refresh()里 调用 invokeBeanFactoryPostProcessors()方法执行后置处理器。
1、此处执行了BeanDefinitionRegistryPostProcessor 和BeanFactoryPostProcessor后置处理器逻辑。
invokeBeanFactoryPostProcessors(beanFactory);
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//执行BeanFactoryPostProcessors后置处理器逻辑
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<>();
//判断是否为BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();
//分别解析出并保存 BeanDefinitionRegistryPostProcessor 和BeanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//得到BeanDefinitionRegistryPostProcessor
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
//得到BeanFactoryPostProcessor
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
//得到所有实现了BeanDefinitionRegistryPostProcessor的类
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//第一步、首先解析实现了PriorityOrdered的类,这部分最先执行
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//注册到容器中
registryProcessors.addAll(currentRegistryProcessors);
//先执行实现了PriorityOrdered的类
// //这里只执行BeanDefinitionRegistryPostProcessors.postProcessBeanDefinitionRegistry()方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空容器中的BeanDefinitionRegistryPostProcessors
currentRegistryProcessors.clear();
// 第二步, 解析实现了Ordered的类后置处理器
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
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();
// 第三步、执行其他BeanDefinitionRegistryPostProcessors后置处理器
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();
}
// 第四步、执行所有类的BeanDefinitionRegistryPostProcessors.postProcessBeanFactory()方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//开始解析执行实现了BeanFactoryPostProcessor接口类的逻辑
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 逻辑同上
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 逻辑同上
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 逻辑同上
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
//执行实现了BeanFactoryPostProcessors接口的方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
beanFactory.clearMetadataCache();
}
5.在refresh()里调用registerBeanPostProcessors()注册beanPostProcessor后置处理器
1、把所有实现了beanPostProcessor接口的类,根据顺序分别保存到容器中
registerBeanPostProcessors(beanFactory);
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
//分别保存实现了PriorityOrdered,Ordered 接口的BeanPostProcessors
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
//得到实现了PriorityOrdered接口的BeanPostProcessor
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
//容器内部的BeanPostProcessor
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
//得到实现了Ordered接口的B没有指定顺序的
orderedPostProcessorNames.add(ppName);
}
else {
//什么排序接口都没实现的BeanPostProcessor
nonOrderedPostProcessorNames.add(ppName);
}
}
//先注入实现了PriorityOrdered接口的BeanPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 然后注入实现了Ordered接口的BeanPostProcessors
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);
// 再注入没实现任何排序接口的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);
// 最后注入容器内部的BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
6.尝试从容器获取bean
在refresh()里 调用 finishBeanFactoryInitialization()开始准备bean的创建
// 工厂信息初始化完成后,开始创建单例非懒加载的bean
finishBeanFactoryInitialization(beanFactory);
- 调用finishBeanFactoryInitialization设置一些工厂配置
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//设置数据格式转换器
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));
}
//添加环境变量解析器到容器中
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
//初始所有需要进行代码植入的对象LoadTimeWeaverAware
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
//设置临时类加载器
beanFactory.setTempClassLoader(null);
//锁定所有bean的配置信息,此后不允许再进行改变
beanFactory.freezeConfiguration();
// 实例化所有非懒加载的bean对象
beanFactory.preInstantiateSingletons();
}
2.调用 DefaultListableBeanFactory.preInstantiateSingletons()方法
1、获取遍历所有bean的配置信息调用getBean()方法获取bean.
2、FactoryBean类型的 bean做一些额外处理。
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Pre-instantiating singletons in " + this);
}
//获取所有bean的定义信息
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 遍历初始化所有 非来加载并且为单例的bean信息
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//实例化所有非抽象、单例非懒加载的对象
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//是否实现了FactoryBean接口对象
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
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()进行bean的实例化
getBean(beanName);
}
}
}
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();
}
}
}
}
调用AbstractBeanFactory.getBean()
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
3.调用AbstractBeanFactory.doGetBean() 获取bean
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
//1、获取bean的真正名称
final String beanName = transformedBeanName(name);
Object bean;
//2、先尝试从容器缓存中获取bean
Object sharedInstance = getSingleton(beanName);
//3、如果容器中包含对应的bean则直接返回
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
//判断返回的bean是否处于创建中
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
//缓存中没有
//1、检查bean是否正在创建
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
//2、如果容器初始化时没有加载对应bean的配置,则尝试从parentBeanFactory获取bean
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// 有参数.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// 无参数
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//3、标记当前bean正在创建中,alreadyCreated中
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//4、获得合并后的bean配置信息
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//5、检查是否为抽象类
checkMergedBeanDefinition(mbd, beanName, args);
//6、先创建需要在当前bean创建之前必须创建的bean,通过@DependsOn("eventListener")注解设置该信息
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 + "'");
}
//保存bean的从属关系,以便于在销毁时进行先销毁;
registerDependentBean(dep, beanName);
//创建在此之前必须创建的bean
getBean(dep);
}
}
//7、创建当前单例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
//4.5.1、创建bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
//4.5.2、返回创建完成的bean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
//==========创建多例bean
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
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);
}
});
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;
}
}
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.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
4.创建bean
在doGetBean()方法中尝试从容器的缓存获取bean,当容器中不存在该bean时候,开始自己创建bean,最终在AbstractBeanFactory.doGetBean() 方法中调用createBean()
//创建当前单例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
//创建bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
});
//返回创建完成的bean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
1、把创建bean交给 AbstractAutowireCapableBeanFactory.createBean()方法。
1、得到bean的配置定义信息。
2、调用resolveBeforeInstantiation()方法检查当前是否对象是否需要进行代理,如需要则直接返回此处创建的代理对象。
3、上一步没有创建代理的话则调用doCreateBean()方法创建bean的实例了。
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
//确保已经解析了bean的定义信息,没有的话则重新创建bean的定义信息
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
//准备需要overrides覆盖的方法
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// ==BeanPostProcessorsBeforeInstantiation 的扩展实现,返回代理对象
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 {
//====正式开始创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException ex) {
// A previously detected exception with proper bean creation context already...
throw ex;
}
catch (ImplicitlyAppearedSingletonException ex) {
// An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry...
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
2、开始创建bean,调用当前类的doCreateBean()方法。
1、调用createBeanInstance()进行bean的实例创建。
2、创建完bean之后执行所有实现了MergedBeanDefinitionPostProcessor后置处理器的逻辑
3、调用populateBean()对bean进行属性注入。
4、对象属性设置完成之后,调用initializeBean()进行BeanPostProcessor、init、Aware 扩展逻辑处理,并最终返回扩展后的对象。
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
//单例bean 先从看缓存里面有没有
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//==创建bean实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//执行所有实现了MergedBeanDefinitionPostProcessor接口的逻辑
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
//检查bean否整处于创建中,并且验证循环引用
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
//===依赖注入
populateBean(beanName, mbd, instanceWrapper);
//===对象生成后执行BeanPostProcessor、init、Aware 相关逻辑, 返回最终暴露出去的bean对象
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.");
}
}
}
}
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
1、构造对象实例,在 doCreateBean()里调用createBeanInstance()。
1、检查方法和参数的权限。
2、根据参数匹配对应的构造方法进行对象的实例化。
instanceWrapper = createBeanInstance(beanName, mbd, args);
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//确保class不为空,并且访问权限为public
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);
}
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) {
//根据带参构造方法实例化bean
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
//默认无参的构造方法、实例化 bean 并设置到Beanwrapper里
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
2、处理MergedBeanDefinitionPostProcessor后置处理器逻辑,在 doCreateBean()里调用applyMergedBeanDefinitionPostProcessors ()。
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);
}
}
}
3、进行属性注入,在 doCreateBean()里调用populateBean()。
1、获取到bean的初始属性值。
2、在属性设置前执行InstantiationAwareBeanPostProcessor后置处理器逻辑,这里可对bean的对象的属性值进行修改。
3、把最后生成的属性值设置到bean里。
populateBean(beanName, mbd, instanceWrapper);
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 {
return;
}
}
boolean continueWithPropertyPopulation = true;
//执行实现了InstantiationAwareBeanPostProcessor接口的逻辑,在设置bean属性前对bean做修改
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//获得属性参数
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//根据类型或名称进行注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 基于名称的自动装配的dd属性值
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 根据类型自动添加属性值
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//拿到对象所有属性值
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// InstantiationAwareBeanPostProcessor 对当前对象属性做扩展处理
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
if (pvs != null) {
//设置bean的属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
4、在在 doCreateBean()里调用 initializeBean()方法执行其他bean的扩展逻辑。
1、执行实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware的逻辑。
2、执行实现了PostProcessors接口postProcessBeforeInitialization()方法。
3、执行实现了InitializingBean的逻辑,然后执行init方法。
4、执行实现了PostProcessors接口postProcessAfterInitialization()方法。
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
//执行实现了Aware接口的业务(BeanNameAware,BeanClassLoaderAware,BeanFactoryAware)
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//==执行bean初始化之前的业务逻辑 (此处会执行实现了PostProcessors接口的对象逻辑)
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//执行实现了InitializingBean 接口和init-method逻辑
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()) {
//==执行bean初始化之后的业务逻辑 (此处会执行实现了PostProcessors接口的对象逻辑)
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
#####1、 populateBean()
1、根据bean的类型或名称进行 bean的依赖属性注入
2、把所有参数设置到bean中去applyPropertyValues()
2、initializeBean()
//对象属性都初始化完成后执行BeanPostProcessor、init、Aware 相关逻辑, 返回最终暴露出去的bean对象
每个流程里面的扩展知识点
上面已经整体了解了IOC容器的创建过程,下面针对每个流程抽离一些扩展知识点,这些扩展知识点可以让我们更灵活的使用IOC容器
容器初始化过程中的扩展知识点
1、执行 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor
位置:见上述节代码
invokeBeanFactoryPostProcessors(beanFactory);
2、注册BeanPostProcessor
位置:见上述节代码
registerBeanPostProcessors(beanFactory);
尝试从缓存获取bean过程中的扩展知识点
1、标记bean正在处于创建中
位置:doGetBean()方法,见上述代码
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
2、@DependsOn 注解逻辑处理
位置:doGetBean()方法,见上述代码
//6、先创建需要在当前bean创建之前必须创建的bean,通过@DependsOn("eventListener")注解设置该信息
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 + "'");
}
//保存bean的从属关系,以便于在销毁时进行先销毁;
registerDependentBean(dep, beanName);
//创建在此之前必须创建的bean
getBean(dep);
}
}
创建bean过程中的扩展知识点
1、AOP扩展核心BeanPostProcessorsAfterInitialization执行节点
位置: createBean()方法,见上述代码
try {
// ==BeanPostProcessorsBeforeInstantiation 的扩展实现,返回代理对象
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
2、MergedBeanDefinitionPostProcessor后置处理器逻辑处理
位置: doCreateBean()方法,见上述代码
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
3、InstantiationAwareBeanPostProcessor后置处理器逻辑处理。
位置: populateBean()方法,见上述代码
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
4、Aware(BeanNameAware,BeanClassLoaderAware,BeanFactoryAware)逻辑处理
位置: initializeBean()方法,见上述代码
invokeAwareMethods(beanName, bean);
5、PostProcessors. before后置处理器逻辑处理。
位置: initializeBean()方法,见上述代码
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
6、InitializingBean 接口和init-method逻辑处理。
位置: initializeBean()方法,见上述代码
invokeInitMethods(beanName, wrappedBean, mbd);
7、PostProcessors. after 后置处理器逻辑处理。
位置: initializeBean()方法,见上述代码
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
7、其他知识点
三级缓存处理循环依赖
singletonObjects 缓存所有的单例bean
singletonsCurrentlyInCreation 缓存正处于创建中的bean缓存
singletonFactories 构造中的bean
代理对象的缓存
advisedBeans 缓存容器中增强的bean
targetSourcedBeans 缓存到容器中的原对象
proxyTypes 缓存代理对象的类型