Spring启动
容器和对象的创建流程
-
先创建容器
-
加载配置文件,封装成BeanDefinition
-
执行BeanFactoryPostProcessor增强器
3.1准备工作
1、注册BeanPostProcessor
2、初始化广播器
3、国际化的相关配置
4、注册监听器
-
对象实例化
-
对象初始化
1、自定义属性赋值
2、容器对象属性赋值
3、调用BeanPostProcessor的前置增强器
4、调用initMethod方法进行初始化方法
5、调用BeanPostProcessor的后置处增强器
-
获取到完整对象
源码详解
ClassPathXmlApplicationContext继承AbstractApplicationContext,执行refresh()方法,自动刷新上下文,加载所有 bean 定义并创建所有单例。
refresh()
AbstractApplicationContext
的refresh()公有12个方法,完成Spring上下文的刷新(包含所有 bean的创建)
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
// 1. 准备上下文刷新
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 2. 获取beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 3. 准备beanFactory,添加一些组件
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 4. 子类扩展设置beanFactory
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 5. 执行 BeanFactoryPostProcessor 方法,beanFactory增强器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 6. 注册 BeanPostProcessors,bean增强器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 7. 初始化 MessageSource 组件(做国际化功能;消息绑定,消息解析)
initMessageSource();
// Initialize event multicaster for this context.
// 8. 初始化事件派发器,在注册监听器时会用到
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 9. 留给子容器(子类),子类重写这个方法,在容器刷新的时候可以自定义逻辑,web 场景下会使用
onRefresh();
// Check for listener beans and register them.
// 10. 注册监听器,派发之前步骤产生的一些事件(可能没有)
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 11. 初始化所有bean实例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 12. 发布容器刷新完成事件
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();
}
}
}
1 准备刷新
容器刷新前的准备工作
-
设置容器启动时间
-
设置激活状态
-
获取到Environment环境对象,并加载当前系统的属性值到Environment环境对象
-
创建监听器集合,默认为空
protected void prepareRefresh() {
// Switch to active.
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());
}
}
// Initialize any placeholder property sources in the context environment.
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
2 获取beanFactory
beanFactory是在执行refresh方法之前创建的。
SpringBoot创建beanFactory
是根据ApplicationContext类型来创建的,Springboot一般是创建AnnotationConfigApplicationContext,AnnotationConfigApplicationContext继承GenericApplicationContext,GenericApplicationContext的构造器里面创建beanFactory(DefaultListableBeanFactory
默认列表beanFactory)。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
ConfigurableApplicationContext context = null;
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
this.configureIgnoreBeanInfo(environment);
Banner printedBanner = this.printBanner(environment);
// 创建beanFactory
context = this.createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, listeners);
throw new IllegalStateException(var10);
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
try {
switch(webApplicationType) {
case SERVLET:
return new AnnotationConfigServletWebServerApplicationContext();
case REACTIVE:
return new AnnotationConfigReactiveWebServerApplicationContext();
default:
return new AnnotationConfigApplicationContext();
}
} catch (Exception var2) {
throw new IllegalStateException("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);
}
};
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
Spring创建beanfatory
万恶之源 new ClassPathXmlApplicationContext()
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("hello");
创建一个新的 ClassPathXmlApplicationContext,从给定的 XML 文件加载定义并自动刷新上下文。
参数:
configLocation - 资源位置
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// 调用父类构造器
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
调用父类构造器,最终会执行到AbstractApplicationContext的构造器
AbstractApplicationContext既实现了BeanFactory接口,又实现了ResourceLoader接口,这两个在Spring中是重中之重,BeanFactory负责创建bean,ResourceLoader负责加载资源。所以AbstractApplicationContext拥有非常多的功能。
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
}
3 准备beanFactory
设置beanFactory的组件等其他属性
set add ignore
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置 classLoader
beanFactory.setBeanClassLoader(getClassLoader());
//设置 bean 表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 添加一个 BeanPostProcessor【ApplicationContextAwareProcessor】
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);
// 注册可以解析的自动装配类,即可以在任意组件中通过注解自动注入
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 添加一个 BeanPostProcessor【ApplicationListenerDetector】
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 添加编译时的 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()));
}
// Register default environment beans.
// 注册 environment 组件,类型是【ConfigurableEnvironment】
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
// 注册 systemProperties 组件,类型是【Map<String, Object>】
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
// 注册 systemEnvironment 组件,类型是【Map<String, Object>】
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
4 子类扩展设置beanFactory
5 执行BeanFactoryPostProcessor 方法,beanFactory增强器
修改和添加一些BeanDefinition信息,自动装配基本实现的环节(ConfigurationClassPostProcessor
)
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
。。。
}
invokeBeanFactoryPostProcessors方法,按照顺序执行,优先级PriorityOrdered、Ordered、没有任何实现的。
其中有个一BeanFactoryPostProcessor——ConfigurationClassPostProcessor
(实现了PriorityOrdered接口),用来处理@Configuration注解,可以将bean注册到BeanDefinitionMap中。
同时也是处理@Component,@ComponentScan,@Bean,@Configuration,@Import的注解的入口,将bean注入进来
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 先执行实现了PriorityOrdered的增强器
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
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);
// 执行BeanDefinition注册增强器
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 执行BeanDefinition注册增强器
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
//调用注册
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}
ConfigurationClassPostProcessor
的postProcessBeanDefinitionRegistry()方法在这里触发。
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
...
// 配置BeanDefinition
processConfigBeanDefinitions(registry);
}
processConfigBeanDefinitions()方法最终处理@Configuration注解的类
大致完成下面操作
- 解析Configuration注解的类,会执行到
AutoConfigurationImportSelector
的process()方法,获取到所有实现了EnableAutoConfiguration
的子类名称
6 注册 BeanPostProcessors,bean增强器
按顺序注册bean增强器,存放到beanFactory的BeanPostProcessors列表中
-
先注册实现了PriorityOrdered接口的 beanPostProcessor
-
再注册实现了Ordered接口的beanPostProcessor
-
再注册常规的beanPostProcessor
-
最后注册 MergedBeanDefinitionPostProcessor类型的beanPostProcessor
此时容器中默认会有6个内置的beanPostProcessor(在无任何代理模式下),还有一些其他的
-
ApplicationContextAwareProcessor
-
ConfigurationclassPostProcessor$ImportAwareBeanPostProcessor
-
PostProcessorRegistrationDelegate$BeanPostProcessorChecker
-
CommonAnnotationBeanPostProcessor
-
AutowiredAnnotationBeanPostProcessor
-
ApplicationListenerDetector
这里只是注册bean增强器,并没有使用,后面创建bean时,会在初始化前后执行bean增强器。
第一次refresh时,还不会将用户自定义的bean增强器注入。后面再次刷新时,才会注入。
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 先注册实现了PriorityOrdered接口的 beanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 再注册实现了Ordered接口的beanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
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);
// Now, register all regular BeanPostProcessors.
// 再注册常规的beanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 最后注册 MergedBeanDefinitionPostProcessor类型的beanPostProcessor
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
7 初始化 MessageSource 组件(做国际化功能;消息绑定,消息解析)
8 初始化事件派发器
Spring 中有很多容器事件,如容器启动、刷新、关闭等。这个功能的实现得益于这里的 ApplicationEventMulticaster
广播器组件,通过它来派发事件通知。
在这里 Spring 也为我们提供了扩展,SimpleApplicationEventMulticaster
默认是同步的。
protected void initApplicationEventMulticaster() {
// 获取 beanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 看看容器中是否有自定义的 applicationEventMulticaster
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
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
// 将创建的 ApplicationEventMulticaster 添加到 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() + "]");
}
}
}
9 子类扩展onRefresh
10 注册监听器
派发之前步骤产生的一些事件
如果用户想监听容器事件,那么就必须按照规范实现 ApplicationListener
接口并放入到容器中,在这里会被 Spring 扫描到,添加到 ApplicationEventMulticaster
广播器里,以后就可以发布事件通知,对应的 Listener 就会收到消息进行处理。
protected void registerListeners() {
// Register statically specified listeners first.
// 获取之前步骤中保存的 ApplicationListener
for (ApplicationListener<?> listener : getApplicationListeners()) {
// getApplicationEventMulticaster() 就是获取之前步骤初始化的 applicationEventMulticaster
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 从容器中获取所有的 ApplicationListener
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
// 派发之前步骤产生的 application events
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
11 初始化所有bean实例
这里是Spring创建bean的核心代码,子类DefaultListableBeanFactory,执行预先实例化bean的操作。
涉及到创建bean的方法,do开头的都是重要方法(一般在抽象类中)
-
getBean
-
doGetBean
-
createBean
-
doCreateBean
-
createBeanInstance 实例化
-
populateBean 填充属性
-
初始化
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.
// 获取容器中的所有 beanDefinitionName
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 循环进行初始化和创建对象
for (String beanName : beanNames) {
// 获取 RootBeanDefinition,它表示自己的 BeanDefinition 和可能存在父类的 BeanDefinition 合并后的对象
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 如果是非抽象的,且单实例,非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 如果是 factoryBean,利用下面这种方法创建对象
if (isFactoryBean(beanName)) {
// 如果是 factoryBean,则 加上 &,先创建工厂 bean
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);
}
}
}
else {
// 不是工厂 bean,用这种方法创建对象
// 一般都是走这种方式创建bean
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
// 所有的bean初始化完成后,回调afterSingletonsInstantiated()方法
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
// 检查所有的 bean 是否是 SmartInitializingSingleton 接口
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
// 回调 afterSingletonsInstantiated() 方法,可以在回调中做一些事情
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
核心
getSingleton
// Eagerly check singleton cache for manually registered singletons.
// 先尝试从3级缓存中获取bean,如果没有就通过下面一种方式获取
Object sharedInstance = getSingleton(beanName);
// Create bean instance.
if (mbd.isSingleton()) {
// 参数2是lambda表达式,如果beanName不在一级缓存中,就执行lambda
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;
}
});
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
然后又开始doCreateBean,此时执行的是子类AbstractAutowireCapableBeanFactory
中的抽象方法
-
实例化bean createBeanInstance
-
将实例化的bean添加到三级缓存 addSingletonFactory
-
填充属性 populateBean(当类的属性是引用对象时,又会createBean,递归操作)
-
初始化bean initializeBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
// 实例化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建bean实例 最终调用Constructor<T> ctor.newInstance(argsWithDefaultValues);
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 将实例化的bean添加到三级缓存中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
// 是否提前暴露bean,可以直接从二级缓存中获取bean
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
实例化createBeanInstance
利用反射,调用Class.getConstructor().new Instance(),实例化bean
BeanUtils.instantiateClass(constructorToUse);
return ctor.newInstance(argsWithDefaultValues);
扩展——获取类的4种方式
- Class.forName(全路径名) 例如com.mysql.jdbc.Driver
- 类名.class
- 对象.getClass()
- 类加载器加载类 任意类名.class.getClassLoader().loadClass(全路径名)
实例化的bean添加到三级缓存 addSingletonFactory
Spring解决循环依赖,默认都是将刚实例化的bean存放到三级缓存中。
填充属性 populateBean
最后执行applyPropertyValues(beanName, mbd, bw, pvs);
如果属性是对象引用类型,又会调用createBean()方法,递归操作
初始化initializeBean
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 1. 调用aware方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 2. 执行初始化bean前置增强器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 3. 执行初始化bean方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 4. 执行初始化bean后置增强器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
1 调用aware方法
实现BeanFactoryAware
接口的类,在这里赋值BeanFactory属性
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
2 执行初始化bean前置增强器
实现ApplicationContextAwareProcessor
接口的类,会在这里赋值属性ApplicationContext
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
问题:BeanFactoryAware
和ApplicationContextAwareProcessor
为什么要分开操作?
BeanFactory和ApplicationContext是不同的接口,ApplicationContext继承了BeanFactory,同时还继承了其它功能接口,如ResourceLoader(资源加载器)、ApplicationEventPublisher(事件发布器),两个的功能不一样,所有要分开操作更好一下。
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
反射
另外有的bean增强器还利用了反射,比如InitDestroyAnnotationBeanPostProcessor,它的子类是CommonAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor的构造器设置了初始和销毁注解
public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);
setInitAnnotationType(PostConstruct.class);
setDestroyAnnotationType(PreDestroy.class);
ignoreResourceType("javax.xml.ws.WebServiceContext");
}
@PostConstruct注解的方法将会被InitDestroyAnnotationBeanPostProcessor(初始销毁注解bean增强器)处理,被存入到LifecycleMetadata类中,保存类信息,init方法、destroy方法信息。
创建bean时,会在初始化之前调用所有的初始化bean前置增强器,其中包括InitDestroyAnnotationBeanPostProcessor,然后使用的反射,执行@PostConstruct注解的方法。
InitDestroyAnnotationBeanPostProcessor是什么时候创建生命周期元信息缓存的?
- refresh(),先注册bean增强器BeanPostProcessor,registerBeanPostProcessors(beanFactory);
- 初始化bean前置增强器,反射调用执行一次(懒新增,并执行)
InitDestroyAnnotationBeanPostProcessor
源码
// 获取clazz的生命周期元数据
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
if (this.lifecycleMetadataCache == null) {
// Happens after deserialization, during destruction...
return buildLifecycleMetadata(clazz);
}
// Quick check on the concurrent map first, with minimal locking.
LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
if (metadata == null) {
synchronized (this.lifecycleMetadataCache) {
metadata = this.lifecycleMetadataCache.get(clazz);
if (metadata == null) {
metadata = buildLifecycleMetadata(clazz);
this.lifecycleMetadataCache.put(clazz, metadata);
}
return metadata;
}
}
return metadata;
}
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
return this.emptyLifecycleMetadata;
}
// 初始化方法列表
List<LifecycleElement> initMethods = new ArrayList<>();
// 销毁方法列表
List<LifecycleElement> destroyMethods = new ArrayList<>();
Class<?> targetClass = clazz;
do {
// this.initAnnotationType = PostConstruct
// this.destroyAnnotationType = PreDestroy
final List<LifecycleElement> currInitMethods = new ArrayList<>();
final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
// 类方法使用了PostConstruct注解,最后存储到LifecycleMetadata,
// 再存储到lifecycleMetadataCache中,key是当前类,value是LifecycleMetadata
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
currDestroyMethods.add(new LifecycleElement(method));
if (logger.isTraceEnabled()) {
logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
}
}
});
initMethods.addAll(0, currInitMethods);
destroyMethods.addAll(currDestroyMethods);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return (initMethods.isEmpty() && destroyMethods.isEmpty() ? this.emptyLifecycleMetadata :
new LifecycleMetadata(clazz, initMethods, destroyMethods));
}
执行初始化bean前置增强器
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
// 执行初始化方法 PostConstruct注解的方法
metadata.invokeInitMethods(bean, beanName);
}
catch (InvocationTargetException ex) {
throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
}
return bean;
}
3 执行初始化bean方法
初始化bean,执行钩子函数 ((InitializingBean) bean).afterPropertiesSet();
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
4 执行初始化bean后置增强器
与初始化bean前置增强器,逻辑一样
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
12 发布容器刷新完成事件
整个容器初始化完毕之后,会在这里进行一些扫尾工作,如清理缓存,初始化生命周期处理器,发布容器刷新事件等。
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.
// 拿到前面定义的生命周期处理器【LifecycleProcessor】回调 onRefresh() 方法
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布容器刷新完成事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}