调用构造函数
调用父类的构造函数,拿到BeanFactory、
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
new出AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner, 在
new AnnotatedBeanDefinitionReader(this);
过程中生成并注册了5个开天辟地的BeanDefinition:
如果没有ConfigurationClassPostProcessor,将无法解析配置类AppConfig。
public AnnotationConfigApplicationContext() {
// 在执行这个构造方法之前,会先执行父类的构造方法,会初始化一个beanFactory = new DefaultListableBeanFactory()
// 生成并注册5个BeanDefinition
// 1.ConfigurationClassPostProcessor
// 2.AutowiredAnnotationBeanPostProcessor
// 3.CommonAnnotationBeanPostProcessor
// 4.EventListenerMethodProcessor
// 5.DefaultEventListenerFactory
this.reader = new AnnotatedBeanDefinitionReader(this);
// 注册默认的includeFilter
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
// 生成并注册5个BeanDefinition
// 1.ConfigurationClassPostProcessor
// 2.AutowiredAnnotationBeanPostProcessor
// 3.CommonAnnotationBeanPostProcessor
// 4.EventListenerMethodProcessor
// 5.DefaultEventListenerFactory
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
注册配置类
即将AppConfig注册为一个BeanDefinition
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
// 1. 创建BeanFactory
// 2. 生成AnnotatedBeanDefinitionReader
// 3. 生成ClassPathBeanDefinitionScanner
this();
// 利用reader把componentClasses注册为一个BeanDefinition
register(componentClasses);
// 调用AbstractApplicationContext的refresh()方法,模板模式,会启动ApplicationContext
// 为什么叫refresh,而不叫start?
refresh();
}
// 最终会调用:
this.beanDefinitionMap.put(beanName, beanDefinition);
// 并且会把BeanName放进一个List里
this.beanDefinitionNames.add(beanName);
Refresh方法(非常非常非常重要!!!最核心)
调用invokeBeanFactoryPostProcessors
会调用开天辟地之ConfigurationClassPostProcessor后置处理器来扫描@Component,得到我们定义的一些类的BeanDefinition,并注册到BeanFactory中。
// Invoke factory processors registered as beans in the context.
// BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
// 默认情况下:
// 此时beanFactory的beanDefinitionMap中有6个BeanDefinition,5个基础BeanDefinition+AppConfig的BeanDefinition
// 而这6个中只有一个BeanFactoryPostProcessor:ConfigurationClassPostProcessor
// 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中
// 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
invokeBeanFactoryPostProcessors(beanFactory); //BeanDefinitionRegistryPostProcessor ,BeanFactoryPostProcessors
调用registerBeanPostProcessors(beanFactory);
注册Bean的后置处理器
调用finishBeanFactoryInitialization(beanFactory);
该方法会完成所以非懒加载的单例Bean的实例化。
该方法就涉及到IOC的所有内容了。
冻结所有的BeanDefinition
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有已经注册了的BeanDefinition,后续不能被修改和处理 beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. // 实例化所有非懒加载的bean beanFactory.preInstantiateSingletons(); }
拿到所有的BeanDefinitionName -> BeanDefiniton - > 生成Bean。
public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans... // 循环bd,实例化单例bean for (String beanName : beanNames) { // userService // 对beanDefinition进行合并,基于合并后的BeanDefinition去创建bean RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 非抽象,单例,非懒加载 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 判断是不是一个SmartFactoryBean if (isFactoryBean(beanName)) { // 如果是一个FactoryBean,那么则获取LubanFactoryBean对象 Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; // eager:急切的意思,立马初始化 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) { // 根据beanName去生成FactoryBean中所生成的Bean对象 getBean(beanName); } } } else { // 根据beanName去创建bean getBean(beanName); } } }
如果不是FactoryBean,就调用getBean来创建Bean,接下来就涉及Bean的生命周期了。
GetBean方法
整体思路:尝试去一级缓存(即单例池)拿Bean,拿到了直接返回,拿不到就去创建。
// Create bean instance.
if (mbd.isSingleton()) {
// 获取单例bean,如果获取不到则创建一个bean,并且放入单例池中
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
// sharedInstance可能是一个FactoryBean,所以需要单独再去factoryBeanObjectCache中去获取对应的对象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
会将该Bean标记成正在创建,然后调用createBean。
CreateBean
调用Bean的后置处理器:
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// beforeInstantiationResolved为null或true
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 实例化前
// Bean的后置处理器
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
Bean的后置处理器可以自己创建Bean,不会让Spring创建某个Bean(可以加判断条件来决定阻止哪个)。
如果没有自己写一个类继承InstantiationAwareBeanPostProcessor,就会由Spring来创建Bean.
doCreateBean
实例化Bean
instanceWrapper = createBeanInstance(beanName, mbd, args);
是通过反射来实现的。
然后填充属性:
populateBean(beanName, mbd, instanceWrapper); //
然后初始化
exposedObject = initializeBean(beanName, exposedObject, mbd);
会去处理Aware,@PostConstruct,InitializingBean,initMethod
最后将Bean加入到单例池中。