十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章主要介绍了BeanPostProcessor怎么在spring中的应用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇BeanPostProcessor怎么在spring中的应用文章都会有所收获,下面我们一起来看看吧。
10多年的东坡网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。营销型网站建设的优势是能够根据用户设备显示端的尺寸不同,自动调整东坡建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联公司从事“东坡网站设计”,“东坡网站推广”以来,每个客户项目都认真落实执行。
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() { @Override public 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); } 6. createBean:483, AbstractAutowireCapableBeanFactory,调用初始化,获取Bean 实例 Object beanInstance = doCreateBean(beanName, mbdToUse, args); 7. doCreateBean:555, AbstractAutowireCapableBeanFactory 进入到具体创建Bean 中 通过populateBean() 进行填充Bean 操作Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd); } } 8.最后可以看到 initializeBean:1620, AbstractAutowireCapableBeanFactory 中 执行 applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization 进行 postProcessBeforeInitialization() 函数和postProcessAfterInitialization() 函数的调用;中间调用 invokeInitMethods(beanName, wrappedBean, 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); } 9. applyBeanPostProcessorsBeforeInitialization:409,AbstractAutowireCapableBeanFactory 最后通过 getBeanPostProcessors() 扫描所有的 BeanPostProcessor 直到遇到null 进行返回退出循环@Override public 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; } 2) 总结 运行过程中的执行原理 通过查看断点调试结果, 可以看到,创建单例容器Bean 通过populateBean() 函数进行填充,invokeInitMethods(beanName, wrappedBean, mbd);函数进行初始化,然后前后有applyBeanPostProcessorsBeforeInitialization 和applyBeanPostProcessorsAfterInitialization 进行对所有的BeanPostProcessor 扫描执行。2.BeanPostProcessor 在spring 中的应用在spring 中大量使用BeanPostProcessor ,进行处理,下面举例3个进行断点、代码测试:1).ApplicationContextAwareProcessor 帮助组件注入IOC 容器在Dog 中实现 implements ApplicationContextAware 接口,编写, setApplicationContext 将容器保存至属性方法中@Componentpublic class Dog implements ApplicationContextAware { private ApplicationContext applicationContext; public Dog(){ System.out.println("dog constructor..."); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub this.applicationContext = applicationContext; }} 1. postProcessBeforeInitialization:97,ApplicationContextAwareProcessor 可以看到 通过 postProcessBeforeInitialization 函数进行将容器进行赋值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); } } } 2).InitDestroyAnnotationBeanPostProcessor 用于处理 @PostConstruct 、@PreDestroy 注解。查看 InitDestroyAnnotationBeanPostProcessor 源码, postProcessBeforeInitialization 函数代码,如下:@Override 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; } 使用 findLifecycleMetadata(bean.getClass()); 获取所有的生命周期函数,通过 metadata.invokeInitMethods(bean, beanName); 进行代理调用对应的生命周期函数public void invokeInitMethods(Object target, String beanName) throws Throwable { Collection 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); } }} 3).BeanValidationPostProcessor 数据校验用于进行数据校验,查看 BeanValidationPostProcessor 的源码 postProcessBeforeInitialization 和 postProcessAfterInitialization 代码如下,进行 doValidate()函数进行数据校验。@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (!this.afterInitialization) { doValidate(bean); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (this.afterInitialization) { doValidate(bean); } return bean; } 关于“BeanPostProcessor怎么在spring中的应用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“BeanPostProcessor怎么在spring中的应用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。 网站题目:BeanPostProcessor怎么在spring中的应用 URL分享:http://mswzjz.cn/article/gseijd.html 其他资讯 linux系统调用原理的示例分析-创新互联 0/1背包问题算法的python实现方式-创新互联 怎么在vue中通过点击事件获取当前点击的元素-创新互联 在安装PHPadmin的过程与遇到的问题及解决方法总结-创新互联 MemoryCompression是什么-创新互联
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); }
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);
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
@Override public 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; }
@Override
public 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;
populateBean() 函数进行填充,invokeInitMethods(beanName, wrappedBean, mbd);
函数进行初始化,然后前后有applyBeanPostProcessorsBeforeInitialization 和applyBeanPostProcessorsAfterInitialization 进行对所有的BeanPostProcessor 扫描执行。
2.BeanPostProcessor 在spring 中的应用
@Componentpublic class Dog implements ApplicationContextAware { private ApplicationContext applicationContext; public Dog(){ System.out.println("dog constructor..."); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub this.applicationContext = applicationContext; }}
@Component
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 stub
this.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); } } }
@Override 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 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); } }}
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (!this.afterInitialization) { doValidate(bean); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (this.afterInitialization) { doValidate(bean); } return bean; }
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) {
关于“BeanPostProcessor怎么在spring中的应用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“BeanPostProcessor怎么在spring中的应用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。