We’ve really loved our iniitial work with Spring. Yesterday we started tying it up with Hibernate, and nothing I’ve seen has been a better solution to configuration and database access. It’s great. We seem to have run into a common misuse case though, and I wanted to jot it down for future reference.

We have existing Struts code that we’re adding some Spring and Hibernate stuff to. We’re using HibernateDaoSupport in creating our own DAOs, but sometimes they throw a NullPointerException when calling getHibernateTemplate(). We go ’round and ’round, but everything seems to be right. We check our *.hbm.xml files, we check our Spring config files, and find nothing. Then we find that our Action class looks something like this:

public ActionForward execute( [...] ) {
   BusinessDelegate delegate = new BusinessDelegate();

I’m sure you’ve already spotted the problem. The whole principle behind the Spring implementation of Inversion of Control (or Dependency Injection) is that your Action class is told which BusinessDelegate to use. If you create your own, it simply isn’t assembled and configured using your Spring setup, and therefore it won’t have the dependencies set properly. And that’s why we’d find NullPointerExceptions.

Ahh. It’s written down. Now I’ll find it faster next time I forget…I hope.

comments powered by Disqus