Peter Bell said the following on 6/19/2007 10:36 AM:
No golden rule. Two general schools of thought:
Use constructor wherever you can and only use setter injection when
you have circular dependencies. The idea is that constructors should
define the “contract” for creating the bean so you should put
everything there unless you are unable to because of circular
dependencies.
Other is use setter for everything (unless you need to call methods in
the bean in the init and therefore have to have it in the
constructor). Principle is that if you don’t have a use case where you
need to call methods in init on injected beans, you can just use
setter for everything so you don’t have to worry about which to use or
refactor if circular dependencies arise.
Actually, I believe the best practice is for CS (at least in my mind
after talking to Chris, Dave and Kurt) to favor setter injection versus
constructor-arg injection. Unless you need something in the init()
method of the bean you are wiring up. However, you can usually get away
with using the init-method attribute option.
<bean name="someService" id="dot.path.to.someService" init-method="setup">
<property name="someOtherService"><ref bean="someOtherService"/></bean>
<property name="thatService"><ref bean=""thatService"/></bean>
</bean>
Order of operations:
1. Create someService
2. Call init() with any constructor args (must resolve dependencies first)
3. Wiring in properties
4. Call init-method (yes, it's a misleading name, but it follows the
Spring DTD here). In my architecture, we call this the setup() method.
As you can see, any setup stuff that heavily relies on other beans can
be done in the setup method.
.Peter