其他分享
首页 > 其他分享> > 在Spring 5中,ContextSingletonBeanFactoryLocator替代

在Spring 5中,ContextSingletonBeanFactoryLocator替代

作者:互联网

我们使用的是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;
    }
}

这是正确的方法还是有其他选择?

解决方法:

在我的遗留应用程序中,它基于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);

Hopefull可以帮助我的鞋子.

该解决方案可能不适用于所有情况.

标签:spring,spring-bean
来源: https://codeday.me/bug/20190522/1153261.html