Spring5源码分析BeanFactoryPostProcessor

编程

上一篇:Spring5源码分析-BeanDefinitionRegistryPostProcessor

BeanFactoryPostProcessor可以完成对BeanDefinition的修改

源码:

public interface BeanFactoryPostProcessor {

/**

* Modify the application context"s internal bean factory after its standard

* initialization. All bean definitions will have been loaded, but no beans

* will have been instantiated yet. This allows for overriding or adding

* properties even to eager-initializing beans.

* @param beanFactory the bean factory used by the application context

* @throws org.springframework.beans.BeansException in case of errors

* 在Spring的标准初始化完成之后,此时所有的符合Spring规则的BeanDefinition已经全部完成加载,但是还没有任何一个Bean被初始化,

* Spring允许咋们可以覆盖或者添加新的属性

*

*/

void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

 

测试用例代码如下:

@Component

@Getter

@Setter

public class ProcessorUser implements BeanFactoryAware {

private BeanFactory beanFactory;

@Value("${name}")

private String name;

@Value("${age}")

private Integer age;

@Override

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

this.beanFactory = beanFactory;

}

}

如果没有BeanFactoryPostProcessor干预的话,默认初始化完成之后的容器中会有一个processorUser对应的ProcessorUser类型的对象。

但我让下面的PostProcessor生效后就会发现 processorUser对应的对象类型是ProcessorCity了

@Component

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

@Override

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

System.out.println("MyBeanFactoryPostProcessor");

BeanDefinition processorUser = beanFactory.getBeanDefinition("processorUser");

processorUser.setBeanClassName("com.jv.spring.postprocessor.entity.ProcessorCity");

}

}

看debug的情况

以上是 Spring5源码分析BeanFactoryPostProcessor 的全部内容, 来源链接: utcz.com/z/510723.html

回到顶部