1.加载启动class类
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
2.三步
public AnnotationConfigApplicationContext(Class>... componentClasses) {
// 父类构造方法创建DefaultListableBeanFactory
// 一步:创建AnnotatedBeanDefinitionReader与ClassPathBeanDefinitionScanner
this();
// 二步:注册componentClasses
this.register(componentClasses);
// 三步:上下文刷新
this.refresh();
}
3.this方法
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
// 注解BeanDefinition读取器:用来读取被注解的bean
// 1.赋值beanNameGenerator:beanName生成器
// 2.赋值scopeMetadataResolver:解释scope注解值
// 3.赋值BeanDefinitionRegistry:注册bean定义
// 4.赋值conditionEvaluator,用于@Conditional注解
// 5.赋值AnnotationAwareOrderComparator(解析order注解)/ContextAnnotationAutowireCandidateResolver(解析lazy注解)
// 6.设置BeanDefinitionHolder,设置六个处理器,用于解析class文件
// -->org.springframework.context.annotation.internalConfigurationAnnotationProcessor Configuration annotation processor
// -->org.springframework.context.annotation.internalAutowiredAnnotationProcessor Autowired annotation processor
// -->org.springframework.context.annotation.internalCommonAnnotationProcessor 管理managed JSR-250 注解处理器
// -->org.springframework.context.annotation.internalPersistenceAnnotationProcessor JPA
// -->org.springframework.context.event.internalEventListenerProcessor @EventListener
// -->org.springframework.context.event.internalEventListenerFactory 管理EventListenerFactory
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
// ClassPath BeanDefinition扫描器:指定路径下的所有class逐一排查,符合的class封装成BeanDefinition
// 1.注册默认的注解过滤器,支持Component/JSR-250 ManagedBean/JSR-330 Named
// 2.赋值resourcePatternResolver,格式解析
// 3.赋值metadataReaderFactory,
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
4.register(componentClasses)
public void register(Class>... componentClasses) {
for (Class> componentClass : componentClasses) {
registerBean(componentClass);
}
}
public void registerBean(Class> beanClass) {
doRegisterBean(beanClass, null, null, null, null);
}
private void doRegisterBean(Class beanClass, @Nullable String name,
@Nullable Class extends Annotation>[] qualifiers, @Nullable Supplier supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
// 启动类变成注解BeanDefinition,里面会把启动类的注解信息封装起来。
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
// condition注解
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
// 支持jdk1.8 supplier
abd.setInstanceSupplier(supplier);
// 解释scope注解
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
// 生成beanName FooBah会变成fooBah X会变成x,但是URL会变成URL
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 解析lazy注解,放入beanDefinition
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
if (customizers != null) {
for (BeanDefinitionCustomizer customizer : customizers) {
customizer.customize(abd);
}
}
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 检查是否需要使用动态代理,使用了动态代理则返回代理BeanDefinition,里面封装了被增强的对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 放入容器的beanDefinitionMap与beanDefinitionNames中
// 别名与beanName绑定
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
5.refresh();
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
// 1.closed设置为false,active设置为true
// 2.模板方法initPropertySources,初始化配置,这里啥也没干
// 3.校验一些必须的参数
// 4.初始化早期的事件监听器和事件
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 提供beanFactory,用于注册bean
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 给beanFactory设置classloader,spel表达式解析器
// 类型转换器
// 添加ApplicationContextAwareProcessor,处理XXXAware
// 忽略XXXAware自动注入
// 添加一些基础的注册依赖对象
// 添加ApplicationListenerDetector,后置处理器,发现监听器(ApplicationListener)
// 利用beanFactory提前注册一些单例bean:environment/systemProperties/systemEnvironment
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 模板方法,留给子类使用
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 添加BeanDefinitionRegistryPostProcessor ConfigurationAnnotationProcessor,执行postProcessBeanDefinitionRegistry方法
// 执行通过ConfigurationAnnotationProcessor加载进来的BeanFactoryPostProcessors
// 解析@Configuration class,里面会扫面所有含有Component/PropertySources/PropertySource/ComponentScans/ComponentScan
// /Import/ImportResourceBean/注解的类(收集材料)
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 解析BeanPostProcessor,前面放置的AutowiredAnnotationProcessor/CommonAnnotationProcessor与
// ApplicationContextAwareProcessor/ApplicationListenerDetector/ImportAwareBeanPostProcessor
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 初始化国际化资源
initMessageSource();
// Initialize event multicaster for this context.
// 初始化事件播放器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 模板方法
onRefresh();
// Check for listener beans and register them.
// 注册监听器(把监听器绑定到多播器上面)
// 发布一些早期的事件
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化非懒加载的bean
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();
contextRefresh.end();
}
}
}