Spring configuration returns home

Remember the early days of XML, when people were all excited about using it to wire up applications? “You can change which implementation is used without changing any code!”

Sure, right, XML isn’t code. It gets packaged in your jar files, with the code. It controls how your application works, like the code. It breaks shit when it is wrong, like the code. Difference is, it’s a lot easier to test the code.

I’m happy to see that Spring is coming full circle and moving configuration back to the code. Not to application code (in-bean annotations), but to separate configuration classes. This keeps the wiring isolated from the application code, while keeping the configuration readable, refactorable, and more testable.

Instead place of XML, we get something like this:


@Configuration
public void ZooConfig {

@Bean
public Goat goat() {
return new GoatImpl();
}

@Bean
public PettingZoo pettingZoo() {
PettingZoo p = new PettingZooImpl(goat(), goat());
p.openForBusiness();
return p;
}

}

Yes, this is a trivial made-up example. What is exciting about it?
– The compiler finds the typos in your class names.
– The IDE (without any special plugins) links between the application code and configuration. I can get from here to the implementation class quickly. The configuration will show up in a “Find Usages” search. If I rename GoatImpl to AnatolianBlackGoat, the configuration will change, because the configuration is code!
– Integration tests instantiate a fully populated PettingZoo without loading Spring, and without duplicating the logic of how to create one.


@Test
public void animalsLikeItWhenIPetThem() {
PettingZoo p = new ZooConfig().pettingZoo();

String result = p.getAnimal().pet();

assertThat(result, is("Maaaaaaaa."));
}

(Caveat: this isn’t a perfect test. In real life, Spring will proxy the ZooConfig and wrap the goat() call to return one singleton Goat every time. The Spring-created PettingZoo has the same Goat twice. My test PettingZoo has two different Goats.)

This new method of Spring config is a welcome admission that XML is code. If it lives with the code, integrates with the code, and can break the application, then the configuration is code. Pointy braces or curly braces, it’s all code. It might as well be in Java. Putting all this glue and wiring in one place is good, decoupling our application classes is good, and the beautiful part is we can have all this and compile-time type checking too. Mmm, cake.

The phrase “configuration classes” has a lovely ring to it. I hope to hear more of it in the future.

Credit to: St Louis JUG and Chris Hardin of OCI, presenter.