tags:

views:

241

answers:

3

I have a "MessageQueue" class. It's just is to queue messages. Beans that need the ability to post messages simply have a MessageQueue property and Spring takes care of injecting it.

The problem is that many beans need to also register themselves as listeners. The list of listener beans cannot be injected into the messageQueue because that would be lead to circular dependencies. Many beans up and down the dependency chain need to post messages and/or listen to messages.

How then could a Spring-powered message queue be implemented in such a way that it does not involve circular dependencies?

A: 

Are you using constructor or setter injection? If you're using setter injection (autowired or not) then you're fine. Spring can resolve circular dependencies. All it does is inject the object before it injects the properties. So if you have such an object injected, it's best practice not to use it in the setter. If you need to do some initialization use @PostConstruct or the InitiazlizingBean interface with the afterPropertiesSet() method.

cletus
Most of my beans use setters, but at least a few are legacy and both have mandatory constructors and cannot be Spring-aware, unfortunately. But definitely a good idea!
CaptainAwesomePants
A: 

When you have a situation that involves wiring up awkward legacy classes with constructors that "do stuff" like setting up listeners, I usually wrap the legacy wotsit in a custom Spring FactoryBean. This would have all the necessary setters, and only instantiates the target object when Spring has finished wiring up the circular dependencies.

Don't be afraid of circular dependencies, Spring handles them elegantly as long as object instantiation and injection is fairly passive. Make good use of @PostConstruct and/or InitializingBean to let Spring's lifecycle do the hard work for you.

skaffman
A: 

Okay, I was worrying about something that was actually fine. Lots of things do in fact depend on the queue, but the queue itself depends on nothing. It has no dependencies of its own, and so does not in any way lead to circular dependency issues. It's just a leaf with lots of parents. Silly of me :-)

CaptainAwesomePants