我们使用的是4.2.x版本的spring,我们正在使用ContextSingletonBeanFactoryLocator来加载bean,如下所示
BeanFactoryLocator bfLocator = ContextSingletonBeanFactoryLocator.getInstance("classpath:customBeanRefFactory.xml");
BeanFactoryReference ref = bfLocator.useBeanFactory("sharedApplicationContext");
BeanFactory beanFactory = ref.getFactory();
((AbstractApplicationContext) beanFactory).getBeanFactory().setBeanClassLoader(CustomSpringBeanFactory.class.getClassLoader());
return (ApplicationContext) beanFactory
我们计划升级到spring 5.0.x并找出ContextSingletonBeanFactoryLocator,并且从Spring 5.0版本中删除BeanFactoryLocator和BeanFactoryReference等类。
那么获取应用程序上下文的建议替代方法是什么?
@Configuration
@ImportResource("classpath:ourxml")
public class OurApplicationConfiguration {
}
public class OurAppicationFactoryProvider {
ApplicationContext context;
public ApplicationContext getApplicationContext() {
if (context == null) {
synchronized (this) {
if (context == null) {
context = new AnnotationConfigApplicationContext(OurApplicationConfiguration.class);
}
}
}
return context;
}
}
这是正确的方法还是有其他选择?
答案 0 :(得分:4)
在基于https://jira.spring.io/browse/SPR-15154所述的BeanFactoryLocator/beanRefContext.xml
机制的旧应用程序中,我添加了一个Singleton
类来创建应用程序上下文并使用该上下文。我的代码是
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public enum SpringContextUtil {
INSTANCE;
ApplicationContext context;
public ApplicationContext getApplicationContext() {
if (context == null)
context = new ClassPathXmlApplicationContext("classpath*:beanRefContext.xml");
return context;
}
}
我替换了
final BeanFactoryReference ref = ContextSingletonBeanFactoryLocator.getInstance().useBeanFactory(contextKey);
AbstractApplicationContext context = ((AbstractApplicationContext) ref.getFactory());
通过
AbstractApplicationContext context = (AbstractApplicationContext)SpringContextUtil.INSTANCE.getApplicationContext().getBean(contextKey);
希望能帮助穿鞋的人。
该解决方案可能不适用于所有情况。