在前几节,我们已经讨论过了,对于beanFactory的拦截修改,我们有两个点:
一个是BeanFactoryPostProcessor;一个则是现在的BeanPostProcessor:
BeanPostProcessor:
postProcessBeforeInitialization是在initMethod以前调用,我们可以在此根据beanName判断是不是自己要拦截的bean,然后引用到bean的实例,对其进行一系列的set操作,在这里进行拦截的自定义操作;
我们看下这个接口的方法是在哪里被调用的;
在AbstractAutowireCapableBeanFactory类中:
根据上述代码我们可以清晰的看见怎个拦截过程,在这个我们可以将其整个过程理解为一个模板模式的灵活应用;
一个是BeanFactoryPostProcessor;一个则是现在的BeanPostProcessor:
BeanPostProcessor:
- package org.springframework.beans.factory.config;
- import org.springframework.beans.BeansException;
- Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
- Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
- }
我们看下这个接口的方法是在哪里被调用的;
在AbstractAutowireCapableBeanFactory类中:
- bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
- invokeInitMethods(beanName, bean, mergedBeanDefinition);
- bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
- public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
- throws BeansException {
- if (logger.isDebugEnabled()) {
- logger.debug("Invoking BeanPostProcessors before initialization of bean '" + beanName + "'");
- }
- Object result = existingBean;
- for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
- BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
- result = beanProcessor.postProcessBeforeInitialization(result, beanName);
- if (result == null) {
- throw new BeanCreationException(beanName,
- "postProcessBeforeInitialization method of BeanPostProcessor [" + beanProcessor +
- "] returned null for bean [" + result + "] with name [" + beanName + "]");
- }
- }
- return result;
- }
- public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
- throws BeansException {
- if (logger.isDebugEnabled()) {
- logger.debug("Invoking BeanPostProcessors after initialization of bean '" + beanName + "'");
- }
- Object result = existingBean;
- for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
- BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
- result = beanProcessor.postProcessAfterInitialization(result, beanName);
- if (result == null) {
- throw new BeanCreationException(beanName,
- "postProcessAfterInitialization method of BeanPostProcessor [" + beanProcessor +
- "] returned null for bean [" + result + "] with name [" + beanName + "]");
- }
- }
- return result;
- }