Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the Pros/Cons of Annotations (non-compiler) compared to xml config files

Tags:

When I look at Java frameworks like Hibernate, JPA, or Spring, I usually have the possibility to make my configuration via an xml-file or put annotations directly in my classes.

I am cosistently asking myself what way should I go.

When I use annotations, I have the class and its configuration together but with an xml I get a bigger picture of my system because I can see all class-configurations.

Annotations also get compiled in some way I guess and it should be quicker than parsing the xml, but on the other hand, if I want to change my configuration I have to recompile it instead of just changing the xml file (which might become even more handy for production environments on customer side).

So, when looking at my points, I tend to go the xml-way. But when looking at forums or tutorials usually annotations are used.

What are your pros and cons?

like image 749
lostiniceland Avatar asked Jul 10 '09 11:07

lostiniceland


2 Answers

A good rule of thumb: anything you can see yourself wanting to change without a full redeploy (e.g. tweaking performance parameters) should really go in something "soft-configurable" such as an XML file. Anything which is never realistically going to change - or only in the sort of situation where you'll be having to change the code anyway - can reasonably be in an annotation.

Ignore any ideas of performance differences between annotations and XML - unless your configuration is absolutely massive the difference will be insignificant.

Concentrate on flexibility and readability.

like image 72
Jon Skeet Avatar answered Oct 06 '22 11:10

Jon Skeet


If you're writing an API, then a word of warning: Annotations can leak out into your public interface which can be unbelievably infuriating.

I'm currently working with APIs where the API vendor has peppered his implementation with Spring MBean annotations, which suddenly means I have a dependency upon the Spring libraries, despite the possibility I might not need to use Spring at all :(

(Of course, if your API was an extension to Spring itself, this might be a valid assumption.)

like image 34
butterchicken Avatar answered Oct 06 '22 13:10

butterchicken