DRY your Spring Beans configuration file
It’s always when you discuss with people that some things that you (or the people) hold for an evidence seems to be a closely-held secret. That’s what happened this week when I tentatively showed a trick during a training session that started a debate.
Let’s take an example, but the idea behind this can of course be applied to many more use-cases: imagine you developed many DAO classes inheriting from the same abstract DAO Spring provides you with (JPA, Hibernate, plain JDBC, you name it). All those classes need to be set either a datasource (or a JPA EntityManager, a Spring Session, etc.). At your first attempt, you would create the Spring beans definition file a such:
Notice a pattern here? Not only is it completely opposed to the DRY principle, it also is a source for errors as well as decreasing future maintainability. Most important, I’m lazy and I do not like to type characters just for the fun of it.
Spring to the rescue. Spring provides the way to make beans abstract. This is not to be confused with the
abstract keyword of Java. Though Spring abstract beans are not instantiated, children of these abstract beans are injected the properties of their parent abstract bean. This implies you do need a common Java parent class (though it doesn’t need to be abstract). In essence, you will shorten your Spring beans definitions file like so:
The instruction to inject the data source is configured only once for the
abstractDao. Yet, Spring will apply it to every DAO configured as having the it as its parent. DRY from the trenches…
Note: if you use two different data sources, you’ll just have to define two abstract DAOs and set the correct one as the parent of your concrete DAOs.