2-Spring 容器创建
重要类
BeanFactory: org.springframework.beans.factory.BeanFactory
,是一个非常纯粹的 bean 容器,它是 IoC 必备的数据结构,其中 BeanDefinition 是它的基本结构。BeanFactory 内部维护着一个BeanDefinition map ,并可根据 BeanDefinition 的描述进行 bean 的创建和管理。
BeanDefinition: org.springframework.beans.factory.config.BeanDefinition
,用来描述 Spring 中的 Bean 对象,如保存对象的类路径、对象的属性。
ApplicationContext: org.springframework.context.ApplicationContext
,这个是 Spring 容器,它叫做应用上下文,与我们应用息息相关。
入口
// 创建ioc容器, sMainConfig为配置类
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
// AnnotationConfigApplicationContext
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
// 读取注解的Bean定义读取器
private final AnnotatedBeanDefinitionReader reader;
// 扫描指定类路径中注解Bean定义的扫描器
private final ClassPathBeanDefinitionScanner scanner;
// 无参构造函数
public AnnotationConfigApplicationContext() {
// 查看new AnnotatedBeanDefinitionReader(this)源码可以发现
// 此时往容器中注入了5个处理器
// ConfigurationClassPostProcessor
// AutowiredAnnotationBeanPostProcessor
// CommonAnnotationBeanPostProcessor
// EventListenerMethodProcessor
// DefaultEventListenerFactory
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
// 最常用的构造函数,通过将涉及的配置类传递给该构造函数,实现将相应配置类中的Bean自动注册到容器中
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
// (1) 调用无参构造函数
this();
// (2) 将配置类信息封装成BeanDefinition对象保存到beanDefinitionMap容器中
register(annotatedClasses);
// (3)刷新容器,触发容器对注解Bean的载入、解析和注册
refresh();
}
}
第一步
调用无参构造函数往容器中注入五个处理器的作用
ConfigurationClassPostProcessor:BeanFactoryPostProcessor
的子类,
1.获取配置类的@ComponentScan(basePackages = {"xxx.xxx.xxx"})
信息,将basePackages下的所有Bean注册到容器中
2.获取配置类中被@Bean
注解标注的方法,并将这些Bean注册到容器中
AutowiredAnnotationBeanPostProcessor:BeanPostProcessor
的子类
用来实现依赖注入的功能,在AbstractAutowireCapableBeanFactory#populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw)
方法中执行
CommonAnnotationBeanPostProcessor
EventListenerMethodProcessor:实现了SmartInitializingSingleton
, ApplicationContextAware
, BeanFactoryPostProcessor
接口。收集容器中所有类中被@EventListener
标注的方法,当有事件发布时,这些被标注的方法会被执行。
@Service
public class UserService {
@EventListener(classes = {ApplicationEvent.class})
public void listener(ApplicationEvent event) {
System.out.println("UserService..." + event);
}
}
调用时机finishBeanFactoryInitialization(beanFactory)
,将所有的Bean实例化之后,遍历所有的Bean,判断Bean是否实现了SmartInitializingSingleton
接口,如果实现了,那么将调用SmartInitializingSingleton#afterSingletonsInstantiated()
方法,该方法用来收集容器中被@EventListener
标注的方法,将这些方法封装成一个ApplicationListener
注册到容器中,context.addApplicationListener(applicationListener)
。
DefaultEventListenerFactory
将类中的某个方法转换成ApplicationListener
类型
第二步
将配置类信息封装成BeanDefinition对象保存到beanDefinitionMap容器中
第三步
刷新容器,触发容器对注解Bean的载入、解析和注册
// AbstractApplicationContext
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1. 刷新前的预处理
prepareRefresh();
// 获取一个BeanFactory(DefaultListableBeanFactory),
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 2. BeanFactory 的预准备
prepareBeanFactory(beanFactory);
try {
// 3. BeanFactory准备完成后的后置处理
postProcessBeanFactory(beanFactory);
// 4. 执行BeanFactoryPostProcessors的方法
invokeBeanFactoryPostProcessors(beanFactory);
// 5. 收集所有的 BeanPostProcessors
registerBeanPostProcessors(beanFactory);
// 6. 初始化上下文中的资源文件,如国际化文件的处理等
initMessageSource();
// 7. 初始化上下文事件广播器
initApplicationEventMulticaster();
// 8.给子类扩展初始化其他Bean
onRefresh();
// 9. 在所有 bean 中查找 listener bean,然后注册到广播器中
registerListeners();
// 10.初始化剩下的单例Bean(非延迟加载的)
finishBeanFactoryInitialization(beanFactory);
// 11. 完成刷新过程,通知生命周期处理器 lifecycleProcessor 刷新过程,同时发出 ContextRefreshEvent 通知别人
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.prepareRefresh();
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 留给子类处理的方法
initPropertySources();
// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// 保存容器中的一些早期的事件
this.earlyApplicationEvents = new LinkedHashSet<>();
}
2.prepareBeanFactory(beanFactory);
BeanFactory 的预准备
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置BeanFactory的类加载器、支持表达式解析的.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 添加一个BeanPostProcessor
// Bean初始化时(initializeBean)用来判断是否实现了ApplicationContextAware、MessageSourceAware等接口
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);
// 注册可以解析的自动装配, 可以在任何Bean中注入这些
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 添加一个BeanPostProcessor
// Bean初始化时(initializeBean)收集实现了ApplicationListener的类
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// // 增加对AspectJ的支持
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册一些默认的环境Bean
// Register default environment beans.
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.postProcessBeanFactory(beanFactory);
BeanFactory准备完成后的后置处理。这是一个空方法,子类可以重写这个方法。
4.invokeBeanFactoryPostProcessors(beanFactory);
通过beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)
和
beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)
获取实现了BeanDefinitionRegistryPostProcessors
接口和BeanFactoryPostProcessors
接口的类,获取过程中会触发Bean的实例化然后执行相应的方法。可以通过实现PriorityOrdered
、Ordered
接口来实现优先级。
先执行postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
方法,
然后执行postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
。
前面提到的ConfigurationClassPostProcessor
类就是实现了BeanDefinitionRegistryPostProcessors
接口,而BeanDefinitionRegistryPostProcessors
继承了BeanFactoryPostProcessors
接口。这个类的作用如下:
1.获取配置类的@ComponentScan(basePackages = {"xxx.xxx.xxx"})
信息,将basePackages下的所有Bean注册到容器中
2.获取配置类中被@Bean
注解标注的方法,并将这些Bean注册到容器中
这一步完成后,所有的Bean都已经注册到容器中,此时只有实现了BeanFactoryPostProcessors的类被实例化了,其它Bean都还没有实例化。通过实现BeanFactoryPostProcessors
接口,我们可以修改BeanDefinition
的一些属性。
5.registerBeanPostProcessors(beanFactory);
获取所有实现了BeanPostProcessor
接口的类,并将这些类保存在一个List列表里面,以便后续使用。可以通过实现PriorityOrdered
、Ordered
接口来实现优先级。此时这些类也会被实例化。Bean初始化时(initializeBean),会执行这些类的postProcessBeforeInitialization(Object bean, String beanName)
方法和postProcessAfterInitialization(Object bean, String beanName)
。
6.initMessageSource();
初始化上下文中的资源文件,如国际化文件的处理等 。判断容器中是否存在id为messageSource并且类型是MessageSource的Bean,如果有则赋值给messageSource,如果没有则自己创建一DelegatingMessageSource
,并注入到容器中。 其实该方法就是初始化一个 MessageSource 接口的实现类,主要用于国际化/i18n。
7.initApplicationEventMulticaster();
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果存在 applicationEventMulticaster bean,则获取赋值
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 没有则新建 SimpleApplicationEventMulticaster,并完成 bean 的注册
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
如果当前容器中存在 applicationEventMulticaster 的 bean,则对 applicationEventMulticaster 赋值,否则新建一个 SimpleApplicationEventMulticaster 的对象(默认的),并完成注册。
8.onRefresh();
预留给 AbstractApplicationContext 的子类用于初始化其他特殊的 bean,该方法需要在所有单例 bean 初始化之前调用。 例如在SpringBoot里面,ServletWebServerApplicationContext实现了这个方法,在这个方法里面开始启动web应用服务器,如Tomcat。
9.registerListeners();
protected void registerListeners() {
// 首先注册指定的静态监听器
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 获取所有ApplicationListener类型的Bean名字然后注册到ApplicationEventMulticaster
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 下面将发布前期的事件给监听器
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
10.finishBeanFactoryInitialization(beanFactory);
初始化剩下的单例Bean(非延迟加载的)
// AbstractApplicationContext
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// ....省略前面的方法
// 初始化剩下的单例Bean(非延迟加载的)
beanFactory.preInstantiateSingletons();
}
最终调用如下方法
// DefaultListableBeanFactory
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("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()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
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); // 此时会触发Bean的实例化
}
}
}
else {
getBean(beanName); // 此时会触发Bean的实例化
}
}
}
// 所有单例的、非懒加载的Bean已经全部实例化
// 收集容器中被@EventListener标注的方法,将这些方法封装成一个ApplicationListener注册到容器中
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();
}
}
}
}
11.finishRefresh()
完成刷新过程,通知生命周期处理器 LifecycleProcessor 刷新过程,同时发出 ContextRefreshEvent 通知别人
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
这个时候IOC容器就创建完成了。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: