spring源码分析之启动流程

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

spring源码分析之启动流程spring源码分析
1、 spring源码中组件介绍:
2、spring启动⼯⼚创建和实例化bean的流程:
下图是spring 容器的关系
分析是基于注解的⽅式,⾮解析spring.xml的⽅式
说明:
AnnotationConfigApplicationContext 是ApplicationContext的⼦类;也是BeanDefinitionRegistry的实现类,即即时spring的ioc容器,也是bd的注册器;
1、创建AnnotationConfigApplicationContext ,参数 AppConfig,调⽤AnnotationConfigApplicationContext 的构造⽅法,
说明:Appconfig是基于注解的⽅式配置bean,功能和spring.xm相同;需要 @ComponentScan和@Configuration⼀起使⽤;假如不使⽤@Configuration注解,会⽣成多例bean;使⽤该注解,当引⽤bean的时候会从spring的单例⼯⼚取出bean。

2、 AnnotationConfigApplicationContext(Class<?>... annotatedClasses){} 构造⽅法,主要有⼀下处理逻辑:
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//1. 初始化bean定义读取器和扫描器;
// 2.调⽤⽗类GenericApplicationContext⽆参构造函数,初始化⼀个BeanFactory:DefaultListableBeanFactory
// 3.注册Spring⾃带的bean,共5个包括: ConfigurationClassPostProcessor
// AutowiredAnnotationBeanPostProcessor CommonAnnotationBeanPostProcessor
// EventListenerMethodProcessor DefaultEventListenerFactory
this();
// 注册AppConfig, ApplicationContext传⼊的配置类
//wl 此处只是注册了 @Configuration 注释的配置类,
// wl register⽅法作⽤是将对应的Bean⽣成BeanDefinition,放到spring容器中;容器是⼀个 map,key是beanName(xml<Bean>标签⾥ id),value是BeanDefinition
register(annotatedClasses);
// wl 刷新容器,主要完成了 @Component 等相关注解注释的bean的初始化⼯作,将bean加载到 spring容器管理
refresh();// 启动容器
}
a、 this()⽅法
public AnnotationConfigApplicationContext() {
// 注册spring ⾃带的bean 5个
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
this.reader = new AnnotatedBeanDefinitionReader(this);最终调⽤⼀下⽅法,注册spring ⾃带的5个后置处理器;
/**
* Register all relevant annotation post processors in the given registry.
* 注册所有的后置处理器
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return a Set of BeanDefinitionHolders, containing all bean definitions
* that have actually been registered by this call
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
//此处为⼀个⽐较器,应该是处理优先级的
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
// 注册 ConfigurationClassPostProcessor
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
// 注册 AutowiredAnnotationBeanPostProcessor
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
// 注册 CommonAnnotationBeanPostProcessor
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
// 注册 EventListenerMethodProcessor
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
// 注册 DefaultEventListenerFactory
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
AnnotationConfigApplicationContext的⽆参构造⽅法,⽤来初始化定义读取器和扫描器
调⽤⽗类GenericApplicationContext⽆参构造函数,初始化⼀个BeanFactory:DefaultListableBeanFactory
这⾥的 AnnotatedBeanDefinitionReader注册了spring⾃带的5个bean,分别为:
ConfigurationClassPostProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
EventListenerMethodProcessor
DefaultEventListenerFactory
ClassPathBeanDefinitionScanner :⼀个bean定义扫描器,它检测类路径上的bean候选对象;
b、 register(annotatedClasses)⽅法,⽅法参数可能为多个,
b.1 循环遍历,注册AppConfig, ApplicationContext传⼊的配置类
b.2 ⽅法内部主要调⽤BeanDefinitionReaderUtils. registerBeanDefinition()⽅法,将配置类转换为对应的 BeanDefination,注册到spring容器中
/**
* Register one or more annotated classes to be processed.
* <p>Calls to {@code register} are idempotent; adding the same
* annotated class more than once has no additional effect.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public void register(Class<?>... annotatedClasses) {
for (Class<?> annotatedClass : annotatedClasses) {
registerBean(annotatedClass);
}
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param annotatedClass the class of the bean
*/
public void registerBean(Class<?> annotatedClass) {
doRegisterBean(annotatedClass, null, null, null);
}
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) { BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 注册bean AppConfig
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
/**
* Register the given bean definition with the given bean factory.
* @param definitionHolder the bean definition including name and aliases
* @param registry the bean factory to register with
* @throws BeanDefinitionStoreException if registration failed
*/
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
// 根据beanName注册 (包括 id name)
String beanName = definitionHolder.getBeanName();
// 注册beanDefiniton
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
}
c、 refresh()属于 AbstractApplicationContext⽅法,spring启动时最终会调⽤该refresh()⽅法,
c.1 refresh()⽅法主要完成bean加载到spring容器的⼯作(⾮@Configuratiion bean修饰的配置bean) @Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 获得刷新的beanFactory
// 对于AnnotationConfigApplicationContext,作⽤:
// 1.调⽤org.springframework.context.support.GenericApplicationContext.refreshBeanFactory,
// 只是指定了SerializationId
// 2.直接返回beanFactory(不⽤创建,容器中已存在)
// 对于ClassPathXmlApplicationContext,作⽤:
// 1.调⽤AbstractRefreshableApplicationContext.refreshBeanFactory
// 2.如果存在beanFactory,先销毁单例bean,关闭beanFactory,再创建beanFactory
// 3.注册传⼊的spring的xml配置⽂件中配置的bean,注册到beanFactory
// 4.将beanFactory赋值给容器,返回beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 准备bean⼯⼚:指定beanFactory的类加载器,添加后置处理器,注册缺省环境bean等
// beanFactory添加了2个后置处理器 ApplicationContextAwareProcessor, ApplicationListenerDetector (new )
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 空⽅法
// 允许在上下⽂的⼦类中对beanFactory进⾏后处理
// ⽐如 AbstractRefreshableWebApplicationContext.postProcessBeanFactory
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 1.通过beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)
// 拿到ConfigurationClassPostProcessor
// 2.通过ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry,注册所有注解配置的bean
// 注册的顺序: @ComponentScan>实现ImportSelector>⽅法bean>@ImportResource("spring.xml")
// > 实现 ImportBeanDefinitionRegistrar (相对的顺序,都在同⼀个配置类上配置)
// 3. 调⽤ConfigurationClassPostProcessor#postProcessBeanFactory
// 增强@Configuration修饰的配置类 AppConfig--->AppConfig$$EnhancerBySpringCGLIB
// (可以处理内部⽅法bean之间的调⽤,防⽌多例)
// 添加了后置处理器 ConfigurationClassPostProcessor.ImportAwareBeanPostProcessor (new)
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截bean创建的后置处理器:
// 1.添加Spring⾃⾝的: BeanPostProcessorChecker (new)以及注册了beanDefinition的两个
// CommonAnnotationBeanPostProcessor AutowiredAnnotationBeanPostProcessor
// 重新添加ApplicationListenerDetector(new ) ,删除旧的,移到处理器链末尾
// 2.⽤户⾃定义的后置处理器
// 注册了beanDefinition的会通过 beanFactory.getBean(ppName, BeanPostProcessor.class) 获取后置处理器
registerBeanPostProcessors(beanFactory);
// 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.
// 实例化所有剩余的(⾮懒加载)单例,此处才是真正地将 singleton类型 bean初始化spring的单例bean对象池 singleObjects中。

//singleObjects 是⼀个map <beanName,singleBean>
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//基于观察者模式,事件多播器将 publish 到事件多波器的事件通知到对应的 listener
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();
}
}
}。

相关文档
最新文档