【问题标题】:Get bean post processors in parent bean factory to process beans in child factories获取父 bean 工厂中的 bean 后处理器来处理子工厂中的 bean
【发布时间】:2011-05-24 04:08:46
【问题描述】:

我有一个父 bean 工厂,我希望其中有一个 BeanPostProcessor 来在子工厂中发布进程 bean。 AFAIK,这在 Spring 中不受支持。我的替代方案是什么? (当然除了在每个子工厂的 XML 中声明后处理器)

【问题讨论】:

  • 我知道除了更加谨慎地使用父子上下文之外,没有其他选择。

标签: spring post-processing


【解决方案1】:

一种“解决方案”是将 bean 后处理器添加到执行父后处理器的子上下文中。这是我们最终使用的技术。这是潜在的危险,而不是 IMO 的最佳 Spring 实践。

/**
 * 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;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2012-08-29
    • 2017-06-17
    • 2019-04-03
    相关资源
    最近更新 更多