Java Code Geeks

Thursday, July 24, 2014

Spring Annotations vs xml configurations

I faced this question myself while working on projects. There are many school of thoughts on this topic, however after practicing both the styles, I have come to a point where I can compile a list of guidelines when to use one vs the other. Here is my guideline


  1. If you follow clean architecture principles, you must have heard uncle Bob repeatedly saying "A good architecture allows us to defer critical decisions like UI,framework,database etc". If you want to use spring as a framework to manage dependencies among your beans, do you want to minimize spring dependencies or want to move out of spring framework in the future? If yes, then go for XML which externalizes the configurations. But then in real world, I have not seen any big project that started as a spring project and then later got converted to a JEE project, so if you are spring shop, no problem to use annotations.
  2. Are you writing a library/API which will be used by many teams? In that case, it is easier for everyone to read and understand the XML config. All the bean dependencies are in one place so it is easier to understand rather than downloading the source code of your library from maven repo and go through the code/annotations.
  3. If you need to use spring transactions, I recommend to use annotation. It is hard for a developer to understand that your methods need transaction if that is externalized to a XML config, rather if it is annotated in your class/methods that is easier to follow and understand.
  4. If it is a considerable size of a project and you care for application startup time, then pay attention to context component scan. It may take long time for spring to scan your classpath, read annotations to load all the annotated beans and their autowired dependencies. 
Conclusion
So both the methods are useful and that is why both of them are supported. Choose one over other or choose both according to your need. You can of course mix both the approaches in one project.

1 comment:

Anonymous said...

But doesn't mixing both approaches give you a hard to comprehend and maintain mess.