在父bean工厂中获取bean post处理器以处理子工厂中的bean

时间:2010-12-12 07:41:13

标签: spring post-processing

我有一个父bean工厂,我想在其中使用BeanPostProcessor在子工厂中发布进程bean。 AFAIK,Spring不支持。我有什么选择? (当然,除了在每个子工厂的XML中声明后处理器)

1 个答案:

答案 0 :(得分:0)

一个"解决方案"是将bean后处理器添加到执行父后处理器的子上下文。这是我们最终使用的技术。这是有潜在危险的,而不是最好的Spring练习IMO。

/**
 * A {@linkplain BeanPostProcessor} that references the BeanPostProcessors in the parent context and applies them
 * to context this post processor is a part of. Any BeanPostProcessors from the parent that are {@link BeanFactoryAware} will
 * have the {@linkplain BeanFactory} from the child context set on them during the post processing. This is necessary to let such post processors
 * have access to the entire context.
 */
public class ParentContextBeanPostProcessor implements BeanPostProcessor {

  private final Collection<BeanPostProcessor> parentProcessors;
  private final BeanFactory beanFactory;
  private final BeanFactory parentBeanFactory;

  /**
   * @param parent the parent context
   * @param beanFactory the beanFactory associated with this post processor's context
   */
  public ParentContextBeanPostProcessor(ConfigurableApplicationContext parent, BeanFactory beanFactory) {
    this.parentProcessors = parent.getBeansOfType(BeanPostProcessor.class).values();
    this.beanFactory = beanFactory;
    this.parentBeanFactory = parent.getBeanFactory();
  }

  /** {@inheritDoc} */
  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    for (BeanPostProcessor processor : parentProcessors) {
      if (processor instanceof BeanFactoryAware) {
        ((BeanFactoryAware) processor).setBeanFactory(beanFactory);
      }
      try {
        bean = processor.postProcessBeforeInitialization(bean, beanName);
      } finally {
        if (processor instanceof BeanFactoryAware) {
          ((BeanFactoryAware) processor).setBeanFactory(parentBeanFactory);
        }
      }
    }
    return bean;
  }

  /** {@inheritDoc} */
  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    for (BeanPostProcessor processor : parentProcessors) {
      if (processor instanceof BeanFactoryAware) {
        ((BeanFactoryAware) processor).setBeanFactory(beanFactory);
      }
      try {
        bean = processor.postProcessAfterInitialization(bean, beanName);
      } finally {
        if (processor instanceof BeanFactoryAware) {
          ((BeanFactoryAware) processor).setBeanFactory(parentBeanFactory);
        }
      }
    }
    return bean;
  }
}