Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextSingletonBeanFactoryLocator alternative in spring 5

We were using 4.2.x version of spring and we are using ContextSingletonBeanFactoryLocator to load bean like below

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

We are planning to upgrade to spring 5.0.x and figured out ContextSingletonBeanFactoryLocator and classes like BeanFactoryLocator and BeanFactoryReference are removed from spring 5.0 release.

So what are the suggested alternatives to get application context?

@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;
    }
}

Is this even right approach or there are other alternatives?

like image 854
Dheeraj Joshi Avatar asked Jan 25 '18 06:01

Dheeraj Joshi


1 Answers

In my legacy application which was based on BeanFactoryLocator/beanRefContext.xml mechanism mentioned at https://jira.spring.io/browse/SPR-15154, I added a Singleton class to create application context and use that context. My code is

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;
    }

}

and I replaced

    final BeanFactoryReference ref = ContextSingletonBeanFactoryLocator.getInstance().useBeanFactory(contextKey);
    AbstractApplicationContext context = ((AbstractApplicationContext) ref.getFactory());

by

AbstractApplicationContext context = (AbstractApplicationContext)SpringContextUtil.INSTANCE.getApplicationContext().getBean(contextKey);

Hopefull that would help someone in my shoes.

The solution might not be applicable to all situation.

like image 195
Ashish Avatar answered Oct 19 '22 12:10

Ashish