Spring注解驱动开发之七——BeanPostProcessor 执行原理、在spring 中的应用
本文包含以下内容:
BeanPostProcessor 执行原理
断点查看
总结运行过程中的执行原理BeanPostProcessor 在spring 中的应用
ApplicationContextAwareProcessor 帮助组件注入IOC 容器
InitDestroyAnnotationBeanPostProcessor 用于处理 @PostConstruct 、@PreDestroy 注解
BeanValidationPostProcessor 数据校验
1.BeanPostProcessor 执行原理
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {this();register(annotatedClasses);refresh();}
// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);
// Instantiate all remaining (non-lazy-init) singletons.beanFactory.preInstantiateSingletons();
getBean(beanName);
// Create bean instance.if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {@Overridepublic Object getObject() throws BeansException {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;}}});bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);if (exposedObject != null) {exposedObject = initializeBean(beanName, exposedObject, mbd);}}
Object wrappedBean = bean;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);}if (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}
@Overridepublic Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {result = beanProcessor.postProcessBeforeInitialization(result, beanName);if (result == null) {return result;}}return result;}
populateBean() 函数进行填充,invokeInitMethods(beanName, wrappedBean, mbd);
函数进行初始化,然后前后有applyBeanPostProcessorsBeforeInitialization 和applyBeanPostProcessorsAfterInitialization 进行对所有的BeanPostProcessor 扫描执行。
2.BeanPostProcessor 在spring 中的应用
public class Dog implements ApplicationContextAware {private ApplicationContext applicationContext;public Dog(){System.out.println("dog constructor...");}public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {// TODO Auto-generated method stubthis.applicationContext = applicationContext;}}
2.通过invokeAwareInterfaces判断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);}}}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {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;}
public void invokeInitMethods(Object target, String beanName) throws Throwable {Collection<LifecycleElement> initMethodsToIterate =(this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);if (!initMethodsToIterate.isEmpty()) {boolean debug = logger.isDebugEnabled();for (LifecycleElement element : initMethodsToIterate) {if (debug) {logger.debug("Invoking init method on bean '" + beanName + "': " + element.getMethod());}element.invoke(target);}}}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {if (!this.afterInitialization) {doValidate(bean);}return bean;}public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {if (this.afterInitialization) {doValidate(bean);}return bean;}
-END-
可以关注我的公众号,免费获取价值1980元学习资料
点击“在看”,学多少都不会忘~
本文分享自微信公众号 - 阿聪的全栈之路(gh_ffab7c84fb0c)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。



