YAML4Spring allows you to use YAML configuration files for spring. Here is a before and after. Before(firstbean.xml):
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="MyFirstBean" class="package.MyFirstBeanClass"> <property name="myField" ref="MySecondBean"/> </bean> <bean id="MySecondBean" class="package.MySecondBeanClass"> </bean> </beans>
After(firstbean.yml):
beans: - id: MyFirstBean clazz: package.MyFirstBeanClass properties: myField: !ref MySecondBean - id: MySecondBean clazz: package.MySecondBeanClass
Please notice that "class" has been changed to "clazz", this is because class is already a property in all Java objects so I couldn't use it ;). Also note the !ref tag, this creates a reference from the first bean to the second bean, given the bean ID of the second bean. YAML4Spring recognizes a few tags, here is the list:
If you were instantiating your own XMLBeanFactory or XMLClasspathApplicationContext objects, then all you'd have to do is replace these with the YAML counterparts:
BeanFactory fact = new YamlBeanFactory(new ClassPathResource("config.yml"));
or
BeanFactory fact = new YamlApplicationContext("context.yml");
If you were using some other framework to load your Spring config for you, you might have to dig a little to find out where you can swap out the factory initialization. Please let me know if you do. In particular, if you were using the AbstractDependencyInjectionSpringContextTests (phewww) for your unit tests, you can just override the loadContextLocations method inside your test like this:
protected ConfigurableApplicationContext loadContextLocations(String[] locations) { return new YamlApplicationContext(locations); }
Below are some more before and after examples
If you don't need a lot of the features of spring and just want something simple, I have also written YamlBeanFactoryLite which does not use any of the Spring core machinery and just relies of Jyaml instead. The usage is similar to YamlBeanFactory:
BeanFactory factory = new YamlBeanFactory(new ClassPathResource("config.yml"));
But the config file would instead look like
annie: &annie !example.Kid name: annie age: 6 friends: - *danny danny: &danny !example.Kid name: danny age: 5 friends: - *annie
Basically it is a YAML representation of a map that maps string IDs to objects, which is essentially what a BeanFactory is.