前言
BeanFactoryPostProcessor和BeanPostProcessor这两个接口都是初始化bean时对外暴露的入口之一,本文也主要是学习具体的细节,以便于实际开发中我们能有效率。
文章目录
BeanFactoryPostProcessor
基本概述
BeanFactoryPostProcessorbean是工厂的bean属性处理容器BeanFactoryPostProcessorbean 的机制可以让我们在 bean 实例化之前修改 BeanDefinition 的机会,我们可以利用这个机会对 BeanDefinition 来进行一些额外的操作,比如更改bean 的一些属性,给Bean 增加一些其他的信息等等操作。
使用方法
自定义一个类,实现BeanFactoryPostProcessor接口,并重写方法,在方法中进行对未定义数据进行操作。
代码实现
这是Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.fys.pojo.User">
<property name="name" value="222"></property>
<property name="age" value="1"></property>
<property name="address" value="hh"></property>
</bean>
<bean id="userDao" class="com.fys.dao.UserDao"></bean>
<bean id="userService" class="com.fys.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean class="com.fys.config.MyBeanFactoryPostProcessor" id="beanFactoryPostProcessor"></bean>
</beans>
//这是我编写的BeanFactoryPostProcessor实现类
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("调用了MyCustomBeanFactoryPostProcessor"+beanFactory);
User user = beanFactory.getBean(User.class);
user.setName("111");
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (int i = 0; i < beanDefinitionNames.length; i++) {
String name=beanDefinitionNames[i];
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
System.out.println("name:"+name+" "+"bd:"+beanDefinition.isSingleton());
}
}
}
//这是测试类
public class TestBeanDefinition {
public static void main(String[] args) {
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("bean.xml");
User user = (User) classPathXmlApplicationContext.getBean("user");
System.out.println(user);
}
}
//这是输出结果
调用了MyCustomBeanFactoryPostProcessororg.springframework.beans.factory.support.DefaultListableBeanFactory@60addb54: defining beans [user,userDao,userService,beanFactoryPostProcessor]; root of factory hierarchy
name:user bd:true
name:userDao bd:true
name:userService bd:true
name:beanFactoryPostProcessor bd:true
User{name='111', age=1, address='hh'}
从案例可以看出postProcessBeanFactory()工作是在 BeanDefinition 加载完成之后,在Bean 实例化之前,其主要作用是对加载 BeanDefinition 进行修改。
注意:在postProcessBeanFactory中,不可以进行bean的实列化。
Spring支持多个postProcessBeanFactory
BeanFactoryPostProcessor是支持排序,一个容器可以同时拥有多个 BeanFactoryPostProcessor,这个时候如果我们比较在乎他们的顺序的话,可以实现 Ordered 接口。
实践代码
//1
public class MyBeanFactoryPostProcessor_1 implements BeanFactoryPostProcessor, Ordered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("调用了MyCustomBeanFactoryPostProcessor_1"+beanFactory);
User user = beanFactory.getBean(User.class);
user.setName("111");
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (int i = 0; i < beanDefinitionNames.length; i++) {
String name=beanDefinitionNames[i];
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
System.out.println("name:"+name+" "+"bd:"+beanDefinition.isSingleton());
}
}
@Override
public int getOrder() {
return 1;
}
}
//2
public class MyBeanFactoryPostProcessor_2 implements BeanFactoryPostProcessor, Ordered {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("调用了MyCustomBeanFactoryPostProcessor_2"+beanFactory);
User user = beanFactory.getBean(User.class);
user.setName("333");
user.setAge(12);
String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
for (int i = 0; i < beanDefinitionNames.length; i++) {
String name=beanDefinitionNames[i];
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
System.out.println("name:"+name+" "+"bd:"+beanDefinition.isSingleton());
}
}
@Override
public int getOrder() {
return 2;
}
}
//实验结果
调用了MyCustomBeanFactoryPostProcessor_1org.springframework.beans.factory.support.DefaultListableBeanFactory@60addb54: defining beans [user,userDao,userService,beanFactoryPostProcessor1,beanFactoryPostProcessor2]; root of factory hierarchy
name:user bd:true
name:userDao bd:true
name:userService bd:true
name:beanFactoryPostProcessor1 bd:true
name:beanFactoryPostProcessor2 bd:true
调用了MyCustomBeanFactoryPostProcessor_2org.springframework.beans.factory.support.DefaultListableBeanFactory@60addb54: defining beans [user,userDao,userService,beanFactoryPostProcessor1,beanFactoryPostProcessor2]; root of factory hierarchy
name:user bd:true
name:userDao bd:true
name:userService bd:true
name:beanFactoryPostProcessor1 bd:true
name:beanFactoryPostProcessor2 bd:true
User{name='333', age=12, address='hh'}
**注意:**多个BeanFactoryPostProcessor如果配置相同的,后着会覆盖前者。有多少个BeanFactoryPostProcessor就要在配置文件配置多少个。
源码分析
从ClassPathXmlApplicationContext入手
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();//refresh初始化ioc容器
}
}
因为postProcessBeanFactory()工作是在 BeanDefinition 加载完成之后,BeanDefinition 加载时在refresh方法中,所以我们进去此方法康康
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();//这里会加载BeanDefinition
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
//开始执行注册到该上下文的BeanFactoryPostProcessors
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
让我们进入postProcessBeanFactory的实现方法,实现方法在PostProcessorRegistrationDelegate 类中。代码如下:
[此源码参考自][https://blog.csdn.net/zhong_xj/article/details/104453775]
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 创建用于存放BeanFactoryPostProcessor的List
List<BeanFactoryPostProcessor> regularPostProcessors =
new LinkedList<BeanFactoryPostProcessor>();
// 创建用于存放BeanDefinitionRegistryPostProcessor的list
List<BeanDefinitionRegistryPostProcessor> registryProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
// beanFactoryPostProcessors拿到的是空
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
//如果是BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors.add(registryProcessor);
}
else {
//否则,只是普通的BeanFactoryPostProcessor,添加到regularPostProcessors(用于最后执行postProcessBeanFactory方法)
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
// 调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
// 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
String[] postProcessorNames = beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class, true, false);
// 遍历postProcessorNames
for (String ppName : postProcessorNames) {
//校验是否实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//获取ppName对应的bean实例, 添加到currentRegistryProcessors中
currentRegistryProcessors.add(beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
//将要被执行的加入processedBeans,避免后续重复执行
processedBeans.add(ppName);
}
}
//进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序)
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors.addAll(currentRegistryProcessors);
//遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//执行完毕后, 清空currentRegistryProcessors
currentRegistryProcessors.clear();
//注册Order的处理器
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 校验是否实现了Ordered接口,并且还未执行过
if (!processedBeans.contains(ppName) &&
beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
//遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
//最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors
boolean reiterate = true;
while (reiterate) {
reiterate = false;
//找出所有实现BeanDefinitionRegistryPostProcessor接口的类
postProcessorNames = beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//跳过已经执行过的
if (!processedBeans.contains(ppName)) {
// 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor。因此这边将reiterate赋值为true, 代表需要再循环查找一次
currentRegistryProcessors.add(beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
//进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序)
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
//遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(
currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
//调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor已经全部处理完毕,下面开始处理容器中的所有BeanFactoryPostProcessor
//找出所有实现BeanFactoryPostProcessor接口的类
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 用于存放实现了PriorityOrdered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors =
new ArrayList<BeanFactoryPostProcessor>();
// 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
List<String> orderedPostProcessorNames = new ArrayList<String>();
// 用于存放普通BeanFactoryPostProcessor的beanName
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
// 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// 跳过已经执行过的
} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//添加实现了PriorityOrdered接口的BeanFactoryPostProcessor
priorityOrderedPostProcessors.add(beanFactory.getBean(
ppName, BeanFactoryPostProcessor.class));
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
//添加实现了Ordered接口的BeanFactoryPostProcessor的beanName
orderedPostProcessorNames.add(ppName);
} else {
//添加剩下的普通BeanFactoryPostProcessor的beanName
nonOrderedPostProcessorNames.add(ppName);
}
}
//调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor
//对priorityOrderedPostProcessors排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//遍历priorityOrderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
//调用所有实现Ordered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> orderedPostProcessors =
new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
//获取postProcessorName对应的bean实例, 添加到orderedPostProcessors, 准备执行
orderedPostProcessors.add(beanFactory.getBean(
postProcessorName, BeanFactoryPostProcessor.class));
}
//对orderedPostProcessors排序
sortPostProcessors(orderedPostProcessors, beanFactory);
//遍历orderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
//调用所有剩下的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors =
new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
//获取postProcessorName对应的bean实例, 添加到nonOrderedPostProcessors, 准备执行
nonOrderedPostProcessors.add(beanFactory.getBean(
postProcessorName, BeanFactoryPostProcessor.class));
}
//遍历nonOrderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
//清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符...
beanFactory.clearMetadataCache();
}
BeanPostProcessor
基本概述
相对于BeanFactoryPostProcessorbean不同,BeanPostProcessor只能在bean只能在初始化后(注意初始化不包括init方法)执行一些操作。
使用方法
自定义一个类,实现BeanPostProcessor接口,并重写方法,在方法中进行对未定义数据进行操作。
代码实现
public class User {
private String name;
private Integer age;
private String address;
public User(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public void init(){
System.out.println("init");
}
public User() {
System.out.println("构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
if(o instanceof User){
System.out.println("前置方法"+s);
}
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
if(o instanceof User){
System.out.println("后置方法"+s);
}
return o;
}
}
<bean id="user" class="com.fys.pojo.User" init-method="init">
<property name="name" value="222"></property>
<property name="age" value="1"></property>
<property name="address" value="hh"></property>
</bean>
<bean class="com.fys.config.MyBeanPostProcessor" id="beanPostProcessor" ></bean>
<bean id="userDao" class="com.fys.dao.UserDao"></bean>
<bean id="userService" class="com.fys.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
//输出结果
构造
前置方法user
init
后置方法user
User{name='222', age=1, address='hh'}
从执行可以看出,时先实列化了这个类,然后在初始化方法前执行pre,初始化方法后执行af。
源码分析
在自定义的BeanPostProcessor打上断点,下图是执行的方法: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4FrnlMKJ-1597326760621)(C:\Users\11864\AppData\Roaming\Typora\typora-user-images\image-20200813212125266.png)]
从上图可以看到 这里是在 运行refresh() 里面方法时触发的
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//执行BeanPostProcessor的相关操作
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
中途过多的繁琐getBean,所以我们跳过先不分析,我们就从 AbstractAutowireCapableBeanFactory 类的 initializeBean 方法开始分析
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
return null;
}
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);//1
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {//判断bean 是不是应用程序自己定义的
//2.执行自定义的beanpostprocessor的before操作
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}
try {
//3.执行init方法
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
if (mbd == null || !mbd.isSynthetic()) {//判断bean 是不是应用程序自己定义的
//4.执行自定义的beanpostprocessor的after操作
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
流程:
-
首先判断 是否设置了SecurityManagers ,如果设置了,就进行相关的权限配置 和 Aware 的扩展
-
如果没有 直接进行 Aware 的扩展 ,Aware 这块就是 对相关的Bean 额外的配置一些响应的属性 ,代码块如下
private void invokeAwareMethods(String beanName, Object bean) { if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware)bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ((BeanClassLoaderAware)bean).setBeanClassLoader(this.getBeanClassLoader()); } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware)bean).setBeanFactory(this); } } }
-
判断bean 是不是应用程序自己定义的,如果不是 ,那就 遍历 运行 BeanPostProcessors 的postProcessBeforeInitialization 方法
if (mbd == null || !mbd.isSynthetic()) {//判断bean 是不是应用程序自己定义的 //2.执行自定义的beanpostprocessor的before操作 wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); } try { //3.执行init方法 this.invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable var6) { throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6); } if (mbd == null || !mbd.isSynthetic()) {//判断bean 是不是应用程序自己定义的 //4.执行自定义的beanpostprocessor的after操作 wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); }
追踪applyBeanPostProcessorsBeforeInitialization和applyBeanPostProcessorsAfterInitialization方法
//调用你设置的前置方法 public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; Iterator var4 = this.getBeanPostProcessors().iterator(); do { if (!var4.hasNext()) { return result; } BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); // 获取所有的BeanPostProcessor对象,执行postProcessBeforeInitialization方法 result = beanProcessor.postProcessBeforeInitialization(result, beanName); } while(result != null); // 然后把执行结果返回 return result; } //调用你设置的后置方法 public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; Iterator var4 = this.getBeanPostProcessors().iterator(); do { if (!var4.hasNext()) { return result; } BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next(); // 获取所有的BeanPostProcessor对象,执行postProcessAfterInitialization方法 result = beanProcessor.postProcessAfterInitialization(result, beanName); } while(result != null); // 然后把执行结果返回 return result; }
追踪invokeInitMethods方法,发现是通过反射调用初始化方法
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = bean instanceof InitializingBean; if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (this.logger.isDebugEnabled()) { this.logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { ((InitializingBean)bean).afterPropertiesSet(); return null; } }, this.getAccessControlContext()); } catch (PrivilegedActionException var6) { throw var6.getException(); } } else { ((InitializingBean)bean).afterPropertiesSet(); } } if (mbd != null) { // invoke 反射执行init方法 String initMethodName = mbd.getInitMethodName(); if (initMethodName != null && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { this.invokeCustomInitMethod(beanName, bean, mbd); } } }