The Circular Bean Reference Problem in Spring 2.0’s Arbitrary Domain Object Wiring

February 6, 2006 – 22:00 | aop, hibernate, java, spring

Spring 2.0 has an exciting new feature that, with AspectJ’s powerful AOP support, allows arbitrary domain objects to be injected with dependencies at the time of creation, even when the domain object is not created by Spring. This feature helps developers avoiding the “Anemic Domain Model” because now domain objects can have references to services or even DAO’s, instead of just some other domain objects.

This particular problem comes when I try to inject a DAO into a domain object (I know it’s some debatable practice, but please just bear me for a moment). So the DO is annotated with @Configurable, its constructor is advised such that, at runtime, after the initialization, the Spring aspect will try to get a reference to the DAO, and sets it into this new DO instance. However, in order to materialize the DAO, which naturally holds a reference to a Hibernate session factory. The session factory needs to be instantiated first – and that, surprisingly, is when I get the “circular bean reference” meltdown.

After one pint of log reading, three shots of source code tracing, and a pinch of hair pulling, this here turns out to be the story: at the session factory initialization time, Hibernate3 needs to know which id value represents an unsaved object. E.g., null, -1, or whatever sensible value depending on the nature of the object and the corresponding table. This value is specified via the ‘unsaved-value’ attribute in the object mapping., and, as suggested by the reference, can usually be omitted safely, for Hibernate3 is very smart and can actually guess the unsaved-value by instantiating a new instance of the DO, which naturally would be intercepted by Spring and be injected with a DAO reference, which naturally would need a reference to the session factory, which naturally would have to guess what the unsaved-value is….

The solution is easy – just add ‘unsaved-value=”null”‘ to the mapping file, to prevent Hibernate from attemping the guess.

Now, I can hear you making some impatient noise – “what’s all this inject-DAO-into-DO business?!” Well, I agree it’s some debatable practice, but then it’s also hardly the point here. I could well have tried to inject a service object into this DO, and the service object could have held a legit reference to some DAO. It would have been the same circular reference, only a larger circle.

Trackback from your site, or follow the comments in RSS.
  1. 2 Responses to “The Circular Bean Reference Problem in Spring 2.0’s Arbitrary Domain Object Wiring”

  2. ?????????? ?????????? ??? Wordpress 2.6.2, ????? ??? ????? ?? ??? http://www.digizenstudio.com.

    ??????? ?????????)

    By morrics on Oct 7, 2008

  1. 1 Trackback(s)

  2. Jun 13, 2009: The Path to Zen Blog Archive The Circular Bean Reference | bean bag chairs

Post a Comment