粗略一看, 它有这么多实现:
可见, 它是多么基础 而重要的一个 接口啊! 它提供了两个方法:
public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException; Object postProcessAfterInitialization(Object var1, String var2) throws BeansException; }
两个方法的名字 都是 postProcessXxxInitialization 的格式, 不是 Before 就是 After, 都是围绕 process Initialization 这个过程来做文章的。 当然, 我有一点不明白的是, 为什么 这里有个post, post作为前缀有 在... 之后的意思(http://skill.qsbdc.com/cigencizhui/328.html),但是在这里,和Before一起使用, 有些难以理解。
如果我们自定义的class 实现了 这个接口, 那么它会在每一个 bean 的实例化前后 各被调用一次。 参见AbstractAutowireCapableBeanFactory 源码:
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(); 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(); result = beanProcessor.postProcessAfterInitialization(result, beanName);// 后处理 } while(result != null); return result; }
这两个方法都是在初始化bean 的时候被调用的:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if(System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean); return null; } }, this.getAccessControlContext()); } else { this.invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if(mbd == null || !mbd.isSynthetic()) { wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); // 前处理 } try { 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()) { wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);// 后处理 } return wrappedBean; }