Friday, May 08, 2009

Spring with annotations - in 2 minutes

I have just recently, today, had my first look at spring with annotations. Up until now I have always had to use spring on VM 1.4 so was unable to take advantage of annotations.

Suffice to say, it is awesome!

Now I know for a lot of you, this might be old news, but it wasn't for me.

So you remember the old xml based spring configuration...

<bean id="serviceLayer" class="za.co.bbd.ct.ServiceLayer">
<property name="businessObject" ref="businessObject">
<property name="xmlConfigured" ref="xmlConfiguredX">
</property>


When using annotations, no nasty xml is required.
@Component
public class ServiceLayer {

private IBusinessObject businessObject;
private IXmlConfigured xmlConfigured;

@Resource(name = "businessObject")
public void setBusinessObject(IBusinessObject businessObject) {
this.businessObject = businessObject;
}

@Resource(name = "xmlConfiguredX")
public void setXmlConfigured(IXmlConfigured xmlConfigured) {
this.xmlConfigured = xmlConfigured;
}
}
Then in your spring xml file the following is required. The good thing is that you can mix annotation and xml based configurations seamlessly.

<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />


<!-- tell spring where to find the beans -->
<context:component-scan base-package="za.co.bbd.ct" />

The default name for the bean is the class name without the package name in camel case, iow that "businessObject" class has this as its annotation:
@Component
public class BusinessObject implements IBusinessObject {

}
And if you'd rather not specify the name of the reference and just match by type:

@Autowired
public void setBusinessObject(IBusinessObject businessObject) {
this.businessObject = businessObject;
}

You can mix xml and annotation based configurations. The definition for xmlConfiguredX is also in the xml...
On a project I was on we used xdoclet to circumvent the lack of annotations (project was on 1.4). We had 100K's worth of generated xml spring configuration files. Annotations would have been so much better!

No comments:

How important is the programming language?

  Python, typescript, java, kotlin, C#, .net… Which is your technology of choice? Which one are you currently working in and which do you wa...