我们继续一步一步的研究pringIOC的步骤
我们还是要写一个创建容器的方法来进入这个流程中
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext=new AnnotationConfigApplicationContext("com.spring.bean");
}
我们正式进入其逻辑
当点击上面的对象的时候 ,会出现下面的构造方法
public AnnotationConfigApplicationContext(String... basePackages) {
//创建工厂组件
this();
//扫描配置
scan(basePackages);
//初始化容器
refresh();
}
看似简单的三个方法,实际却庞大无比
this()
实际上就是创建了下面两个方法执行需要的两个组件
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
scan(basePackages)
@Override
public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
Assert.notEmpty(basePackages, “At least one base package must be specified”);
仅仅是对传进来的参数作了一个是否为空的判断,如果为空则抛出异常以及其message
this.scanner.scan(basePackages);
点击这个scan方法,调用ClassPathBeanDefinitionScanner的一下方法
public int scan(String... basePackages) {
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
doScan(basePackages);
// Register annotation config processors, if necessary.
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
- int beanCountAtScanStart = this.registry.getBeanDefinitionCount();
记录bean配置信息的个数 - doScan(basePackages); 调用本类(ClassPathBeanDefinitionScanner)中的doScan方法
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
//这里调用了一次Assert的非空判断抛异常的操作
Assert.notEmpty(basePackages, "At least one base package must be specified");
//创建一个有序的非重复的 LinkedHashSet集合进行bean的保存 其中的对象是存储一个bean的各种属性(作用域,bean名称等属性)
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
//BeanDefinitionHolder 包含对象BeanDefinition ,BeanDefinition 属于BeanDefinitionHolder的一个属性
for (String basePackage : basePackages) {
//扫描对应包下的Components注解资源,把资源文件放到BeanDefinition配置里(需要了解)
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
//解析bean的scope作用域(需要了解)
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
//将所属作用域放入BeanDefinition
candidate.setScope(scopeMetadata.getScopeName());
//生成bean的名称
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
//判断candidate是否是AbstractBeanDefinition的一个实例
if (candidate instanceof AbstractBeanDefinition) {
//设置bean的一些默认属性,lazy,init,destory方法等(需要了解)
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
//通过解析类设置bean的一些属性,lazy,Primary,DependsOn等
//判断candidate是否是AnnotatedBeanDefinition的一个实例
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
//创建BeanDefinitionHolder对象保存提取bean的所有属性,并传入BeanDefinition(candidate)对象和beanName
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;
}
- 调用Set candidates = findCandidateComponents(basePackage);目的是扫描带有@Compont注解的bean,实际上走的是点击find方法中的最下面的那个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;
}
- 最后调用registerBeanDefinition(definitionHolder, this.registry);
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}
最终调用BeanDefinitionReaderUtils类的registerBeanDefinition()方法进行配置注册工作
1、解析bean的Id 和别名
2、调用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);
}
}
}
- refresh();容器初始化操作
点击进入AbstractApplicationContext的refresh()方法
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();
}
}
}
- 3.1 : 容器预处理操作
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<>();
}
- 3.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;
}
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.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());
}
}
- 3.4 : 在refresh()里 调用 invokeBeanFactoryPostProcessors()方法执行后置处理器。
此处执行了BeanDefinitionRegistryPostProcessor 和BeanFactoryPostProcessor后置处理器逻辑。
invokeBeanFactoryPostProcessors(beanFactory);
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
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();
}
- 3.5 : 在refresh()里调用registerBeanPostProcessors()注册beanPostProcessor后置处理器
把所有实现了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));
}