我有一个父 bean 工厂,我想要一个 BeanPostProcessor 来在子工厂中发布进程 bean。AFAIK,这在 Spring 中不受支持。我的替代方案是什么?(当然除了在每个子工厂的 XML 中声明后处理器)
问问题
1405 次
1 回答
0
一种“解决方案”是将 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;
}
}
于 2015-03-24T20:56:38.130 回答