gpt4 book ai didi

spring - 获取父bean工厂中的bean后处理器来处理子工厂中的bean

转载 作者:行者123 更新时间:2023-12-03 17:59:34 25 4
gpt4 key购买 nike

我有一个父 bean 工厂,我想要一个 BeanPostProcessor 来在子工厂中发布处理 bean。 AFAIK,这在 Spring 中不受支持。我的选择是什么? (当然要在每个子工厂的 XML 中声明后处理器除外)

最佳答案

一种“解决方案”是向执行父后处理器的子上下文添加一个 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;
}
}

关于spring - 获取父bean工厂中的bean后处理器来处理子工厂中的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com