Thursday, October 25, 2012

XML vs Annotations

XML
Annotations
More verbose because has to duplicate a lot of information like class names and method names from your code.

Less verbose since class names and method names are part of your code.
Less robust due to duplication of information which introduces multiple points for failure. If you misspell a method name then the application will fail.
More robust because annotations are processed with your code and checked by the compiler for any discrepancies and
inaccuracies.

More flexible since processed separately from the code.
Since it is not hard-coded can be changed later. Your deployment team has a great flexibility to inspect and modify the configuration.
Less flexible since annotations are embedded in Java comment style within your code.

For example, to define a stateless session EJB 3.0 with annotations, which can serve both local and remote clients:

@Stateless
@Local ({LocalCounter.class})
@Remote ({RemoteCounter.class})
public class CounterBean implements LocalCounter,
RemoteCounter {
...
}

XML files can express complex relationships and hierarchical structures at the expense of being verbose.

Annotations can hold only a small amount of configuration information and most of plumbing has to be done in the framework.


Which one to use? Annotations are suitable for most application needs. XML files are more complex and can be used to address more advanced issues. XML files can be used to override default annotation values. Annotations cannot be used if you do not have access to source-code. The decision to go with annotation or XML depends upon the architecture behind the framework.

For example Spring is primarily based on XML and EJB 3.0 is primarily based on annotations, but both support annotations and XML to some degree. EJB 3.0 uses XML configuration files as an optional overriding mechanism and Spring uses annotations to configure some Spring services.

No comments:

Post a Comment