I don’t tend to use it myself (preferring the “spec” mechanism built-in to Stringtree), but today someone asked me if a Mojasef application could work with Spring.
After a bit of thought, some downloading, and a little playing, here is the result. My intention was to allow beans configured in a Spring application context to act as first-class citizens within a Stringtree context, so that they can be used seamlessly inside Mojasef application code and templates.
The implementation was actually pretty simple, essentially consisting of creating a class which implements org.stringtree.Fetcher and provides access to any Spring beans within a Spring context.
package org.stringtree.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.stringtree.Fetcher;
public class SpringFetcher implements Fetcher {
private BeanFactory factory;
public SpringFetcher(BeanFactory factory) {
this.factory = factory;
}
public Object getObject(String name) {
Object ret = null;
try {
ret = factory.getBean(name);
} catch(BeansException e) {
ret = null;
}
return ret;
}
}
To use this class, you will need to create an instance of it, passing in a Spring BeanFactory or ApplicationContext object to the constructor. Then the SpringFetcher object can be used just as any other Fetcher.
It seems that when using Spring in a Mojasef application, what will likely be needed is a single Mojasef context which provides access to both Mojasef and Spring objects. To achieve this, simply wrap the two Fetchers in a FallbackFetcher:
Fetcher spring = new SpringFetcher(new XmlBeanFactory(new FileSystemResource("application.xml")));
Fetcher map = new MapFetcher();
Fetcher ff = new FallbackFetcher(spring, map);
An example Eclipse project containing the SpringFetcher class, some unit tests, and the jar files to compile and run them is available in sourceforge subversion at https://svn.sourceforge.net/svnroot/stringtree/projects/spring_example/trunk.
Posted by Stringtree in Mojasef, Projects
