Friday, March 27, 2009

A trick to guarantee Spring load order without using depends-on

There are times when you want one Spring bean instantiated before another. If bean A depends on bean B, you are guaranteed that B will be instantiated before A. But what if there is no such dependency? In older (i.e. pre-annotation) versions of Spring, the solution is to use the depends-on attribute in the bean definition in your application context. But if you are using annotations exclusively, depends-on isn't available.

The trick is simple: inject an unused dependency using @Resource.

public class A
private B unusedButNeededForSpringBeanLoadOrder;

1 comment:

Roger og Julia Jakobsen said...

This actually helped me! Thanks for posting it!
Why did you put the annotation on a methodheader, I put it on the classheader instead. It seems to work, and I find it to be more intuitive.