Tuesday, September 29, 2009

Annotations or XML

I just commented on a post at stackoverflow asking for suggestions of criteria which should be used to compare the annotation or xml approach when configuring classes for hibernate or spring. Saying then that a decision will be reached on which one is "better".

I responded to the post and you can see it here.

While an interesting academic exercise, I don't foresee it having any real value. The decision on whether to go annotations or xml is made solely on a case by case basis.

But then I asked myself, what are the conditions under which xml/annotations are used with reference to configuring spring beans.

I was on a project where we had hundreds of beans - we were working under Java 1.4 so could not use annotations. We went so far as to use xdoclet where you add the annotation information as javadoc tags in an attempt to account for this constraint. It wasn't ideal as you have to generate the xml from the source code and thus the xml can easily be out of sync - don't have to do that when using annotations.

So in that context, annotations won, and to my mind, for many "workhorse" beans it's a no brainer. Maintaining the xml for hundreds of beans where no custom configuration is required, annotations is definitely better. Annotations handle refactoring, method name changes, classname changes, even certain structural changes require no adjustment to the annotations.

So is xml now defunct, have annotations killed the xml star?

No - there are two contexts where I am essentially forced to use xml.
1. Where I want to customise configuration.
So I want to be able to specify different values for beans, or if I want to change the bean I'm injecting into another bean. I want to be able change property values. Doing this with annotations though possible would be too unwieldy. While it's possible to run Windows Vista, that doesn't make it a good idea.
2. Where I don't have access to the source code of the classes I want to create as beans i.e. where I want to re-use classes from other libraries.
Because I don't have access to the source code and/or I want to potentially create more than one bean from the same class, xml is the preferred approach here. The key difference between xml and annotations it that when using annotations I do not have to specify the details of the class, i.e. I do not have to contextualise the information I'm adding, it is already contextualised because it is connected with a class, field or method. With xml I always have to add this contextualising information.

In my current project I have a small xml file which has all the beans created from re-usable components in it, and that's all. Everything else is done via annotations.

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...