Monday, August 22, 2005

Spring/Hibernate Training 2

Five ways to wire up collaborators

This must be in the spring manual somewhere. But, well, who reads manuals? So here are the five ways to inject dependencies (and some of my thoughts):

First, via constructors. This would make an oject purist happy, as the objects would be in a consistent state after construction. The drawback is if you have more than one constructor argument, even just two or three, your context file becomes hard to understand. For example

<bean id="foo" class="somepackage.Foo">
<constructor-arg><ref bean="bar"/></constructor-arg>

That wasn't very clear, was it?

Which brings us to the second way to inject dependencies: via setters. People usually raise objections when they first run into this: your ojects are invalid! You have to remember to call the setters after you construct them! But in reality, you get used to them after a while. This looks so much clearer:

<bean id="foo" class="somepackage.Foo">
<property name="bar"><ref bean="bar"/></property>
<property name="intValue"><value>1</value></property>
<property name="booleanValue"><value>true</value></property>

The last three methods are all through autowiring, eith by type, by name or by constructor arguments (which can only be by type). These are cool for fast prototypes, as everything is wired together like magic. But in a production environment, it's going to be a nightmare for others to understand and maintain your context files.


Post a Comment

<< Home