Archive

Archive for January, 2009

Add spring managed beans library dynamically into a context

Problem:

We want to section an application into small modules (packaged as jars). The most ones containing spring managed bean and one conteining the code for recover them.

Solution:

The core of the jar containing the code for beans recovering was this:

public static Object getBean(String beanId, String beanFactoryName) {
        BeanFactoryLocator locator = getSingletonBeanFactoryLocator();
        BeanFactoryReference bf = locator.useBeanFactory(beanFactoryName);
        return bf.getFactory().getBean(beanId);
    }

    private static BeanFactoryLocator getSingletonBeanFactoryLocator(){
        String s = "beanFactory.xml";
        BeanFactoryLocator res = org.springframework.beans.factory.access.SingletonBeanFactoryLocator.getInstance(s);
        return res;
    }

The key is the use of the class SingletonBeanFactoryLocator. It arranges the content of all the files named “beanFactory.xml” loaded by the classloader, so present everywhere in the classpath’s root positions, in a single context. So adding seamlessly a new library containig spring managed beans to application context it’s simple: you have to create a jar including a beanFactory.xml in the default package… that’s all! The beans will be loaded automatically in the context using the SingletonBeanFactoryLocator methods.

Categories: Uncategorized