2010-12-12 9 views
5

親Beanファクトリを持っています。子BeanファクトリにプロセスBeanをポストするBeanPostProcessorが必要です。 AFAIK、これはSpringではサポートされていません。私の選択肢は何ですか? (各子ファクトリのXMLにポストプロセッサを宣言することを除いて)親BeanファクトリのBeanポストプロセッサを子ファクトリのBeanを処理するために取得する

+0

親子コンテキストをより控えめに使用する以外に、私が認識している他の方法はありません。 – skaffman

答えて

0

"解決策"の1つは、親ポストプロセッサを実行する子コンテキストにBeanポストプロセッサを追加することです。これが私たちが使い終わったテクニックです。それは潜在的に危険であり、最高の春練習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; 
    } 
} 
関連する問題