Spring实例化Bean的顺序
说明:这里仅仅是指Spring中的Bean变为Bean对象后对其的各项切入的过程,不涉及对BeanDefinition的切入
实例化Bean的整个过程
- 正常情况下我们仅仅能看到前7个步骤,后面的3个步骤是bean的销毁过程,只有在应用程序调用ApplicationContext.close()方法时才会触发
Demo
// 实验实例
public class LifeCycle implements InitializingBean, DisposableBean {
@Autowired
private void setApplication(ApplicationContext context){
System.err.println("Autowired context:"+context.hashCode());
}
public LifeCycle(){
System.err.println("LifeCycle newInstance...");
}
public void init(){
System.err.println("initMethod...");
}
public void destroy1(){
System.err.println("destroyMothod...");
}
@Override
public void destroy() {
System.err.println("DisposableBean destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.err.println("InitializingBean afterPropertiesSet...");
}
@PostConstruct
public void init3(){
System.err.println("@PostConstruct...");
}
@PreDestroy
public void destroy3(){
System.err.println("@PreDestroy...");
}
}
// BeanPostProcessor对bean的实例化过程进行扩展
public class LifeCycleProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.err.println("LifeCycleProcessor postProcessBeforeInitialization..."+beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.err.println("LifeCycleProcessor postProcessAfterInitialization..."+beanName);
return bean;
}
}
// 配置类
@Configuration
public class LifeCycleConfig {
@Bean(initMethod = "init",destroyMethod = "destroy1")
public LifeCycle lifeCycle() {
return new LifeCycle();
}
}
public class MainTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class, LifeCycleProcessor.class);
System.err.println("————————————————————");
context.close();
}
}
- 运行MainTest中的main函数,则会打印如下内容
LifeCycle newInstance...
Autowired context:1915058446
LifeCycleProcessor postProcessBeforeInitialization...lifeCycle
@PostConstruct...
InitializingBean afterPropertiesSet...
initMethod...
LifeCycleProcessor postProcessAfterInitialization...lifeCycle
————————————————————
@PreDestroy...
DisposableBean destroy...
destroyMothod...
实例化Bean中的各部分关键Spring源码(对应上述流程图的前7个)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 以该方法为起源开始
1. newInstance()
说明:可以看到实例化时,先从factoryBean创建的实例缓存中取出并移除,如果没有则进行创建
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
// createBeanInstance()主要内容
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
根据createBeanInstance主要内容,可以看到实例化Bean的分很多中情况:判断是否使用工厂方法创建、判断是否已经解析过(如果解析过且有有参构造方法则通过有参构造Autowired注入,如果解析过且没有有参构造方法则通过无参构造注入),如果未解析过,判断是否有多个构造方法或注入模式为构造器注入或有有参构造方法或参数值不为空则通过Autowired自动注入,否则通过无参构造方法实例化
2. Autowired 注入属性
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean 方法中的populateBean 为bean实例注入Autowired修饰的属性或方法
populateBean(beanName, mbd, instanceWrapper);
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
3. 初始化Bean,对bean实例化之后执行一些额外的初始化方法回调
// 注入属性后执行初始化bean的一些操作,步骤如下
// 1.执行BeanPostProcessor的postProcessBeforeInitialization()方法
// 2.判断是否实现了InitializingBean,如果实现了则将其转为InitializingBean并调用afterPropertiesSet()方法
// 3.判断是否有指定的initMethod方法名,如果有且(方法名不是afterPropertiesSet且实现了InitializingBean且方法名不是额外管理的初始化方法)则调用
// 4.执行BeanPostProcessor的postProcessAfterInitialization()方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
// 以下是initializeBean的主要内容,可以看出初始化Bean的整个过程
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
// 调用所有BeanPostProcessor中的postProcessBeforeInitialization()方法
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 调用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
// 调用调用所有BeanPostProcessor中的postProcessAfterInitialization()方法
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
// 就是从工厂中获取所有的BeanPostProcessor并调用其postProcessBeforeInitialization方法
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
3-0 ApplicationContextAwareProcessor处理实现Aware接口的类
由于EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware接口也实现了Aware接口,所以实现这些接口的类也都间接实现了Aware接口
这里ApplicationContextAwareProcessor优先执行是因为在AbstractApplicationContext#prepareBeanFactory()这个方法里执行了beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));将其优先加入了beanPostProcessor列表中,同时还有beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));加入了ApplicationListenerDetector用来处理实现了ApplicationListener的bean
- ApplicationContextAwareProcessor的postProcessBeforeInitialization() 详细内容
// org.springframework.context.support.ApplicationContextAwareProcessor#postProcessBeforeInitialization
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
3-1 InitDestroyAnnotationBeanPostProcessor 处理@PostConstruct注解,并执行其修饰的方法
由于Spring内置的一个CommonAnnotationBeanPostProcessor实现了InitDestroyAnnotationBeanPostProcessor,该InitDestroyAnnotationBeanPostProcessor可以用来处理@PostConstruct注解,且会在自定义BeanPostProcessor之前执行
- CommonAnnotationBeanPostProcessor继承图
- InitDestroyAnnotationBeanPostProcessor继承图
- InstantiationAwareBeanPostProcessor及BeanFactoryAware继承图
由于这里InitDestroyAnnotationBeanPostProcessor实现了PriorityOrdered,且order的值为Ordered.LOWEST_PRECEDENCE,即2147483647,权重最低,所以会在所有实现了PriorityOrdered接口的BeanPostProcessot的最后执行,因此如果需要得到处理后的对象,使用@PostConstruct来修饰方法进行赋值而不是通过@Autowired的方式注入
- InitDestroyAnnotationBeanPostProcessor的切入bean实例化过程的具体内容如下
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 获取LiftcycleMetadata,从而调用其initMethod方法
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
try {
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;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
- 主要看下其中的findLifecycleMetadata,获取所有方法上有@PostConstruct/@PreDestroy,并将其方法加入到initMethods和destroyMethods
// org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#findLifecycleMetadata
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) {
// 从该类的类型中构建一个LifecycleMetadata
metadata = buildLifecycleMetadata(clazz);
this.lifecycleMetadataCache.put(clazz, metadata);
}
return metadata;
}
}
return metadata;
}
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
final boolean debug = logger.isDebugEnabled();
List<LifecycleElement> initMethods = new ArrayList<>();
List<LifecycleElement> destroyMethods = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<LifecycleElement> currInitMethods = new ArrayList<>();
final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
// 遍历所有的方法,判断方法上是否有@PostConstruct、@PreDestroy注解
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
LifecycleElement element = new LifecycleElement(method);
currInitMethods.add(element);
if (debug) {
logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);
}
}
if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
currDestroyMethods.add(new LifecycleElement(method));
if (debug) {
logger.debug("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 new LifecycleMetadata(clazz, initMethods, destroyMethods);
}
3-3 执行AbstractAutoProxyCreator中的postProcessBeforeInitialization()
AOP功能就是在此实现的
- 继承AbstractAutoProxyCreator的类有以下几个
- AbstractAutoProxyCreator是一个抽象类,但是它里面有postProcessBeforeInstantiation()用来处理切面和切入点并为其创建代理类(及目标类)并返回,源码如下
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = this.getCacheKey(beanClass, beanName);
if(beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if(this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if(this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
if(beanName != null) {
TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
if(targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}
return null;
}
3-N 执行自定义的BeanBostProcessor中的postProcessBeforeInitialization()
4 调用InitMethods方法
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 判断是否实现了InitializingBean接口
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("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 {
// 调用其afterPropertiesSet()方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
// 获取该BeanDefinition上指定的initMethod方法名,然后去通过反射调用
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
4-1 判断是否是InitializingBean类型,如果是将其转为InitializingBean并调用afterPropertiesSet()方法
通过 bean instanceof InitializingBean 进行判断,通过 ((InitializingBean) bean).afterPropertiesSet(); 完成方法调用
4-2 获取该BeanDefinition上指定的initMethod方法名,然后去通过反射调用
通过mbd.getInitMethodName();可以得到@Bean上指定的initMethod="xx"或xml配置上的init-method=“xx”
5 执行所有BeanPostProcessor的postProcessAfterInitialization()方法
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
5-0 调用ApplicationContextAwareProcessor的postProcessAfterInitialization()方法
由于直接返回了,因此这里并没有做什么事
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
5-1 调用InitDestroyAnnotationBeanPostProcessor的postProcessAfterInitialization()方法
由于直接返回了,因此这里并没有做什么事
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}