xml vs annotation - technoangel/java GitHub Wiki

XML vs. Annotations

Annotations

Pros

  • Shorter, concise configuration
  • Dependencies closer to source
  • Ensure type-safety
  • Self-documentation

Cons

  • Strewn all over source
  • Changes require recompilation
  • Less control over configuration
  • Clutter POJOs with metadata

XML

Pros

  • XML helps with separation of concerns.
    • The blueprint is separate from the code
    • The blueprint is in a single location
    • Changes do not require a recompilation
  • XML centralizes metadata
  • More verbose is easier for beginners

Cons

  • Error-prone
  • No type validation

Examples:

<bean id="myorg" class="com.spring.myproject.domain.Organization">
  <constructor-arg value="${org.companyName}" name="companyName"></constructor-arg>
  <constructor-arg value="${org.year}" name="year"></constructor-arg>
  <property value="${org.employeeCount}" name="employeeCount"></property>
</bean>

Example XML Configuration: verbose, clear, unified
package com.spring.myproject.domain;

@Component
public class Organization {
  @Value("${nameOfCompany}")
  private String companyName;
  @Value("#{startUpYear}")
  private int year;
  @Value("${empCount:22222}")
  private int employeeCount;
}

Example Annotation Configuration: small, succinct, colocated
⚠️ **GitHub.com Fallback** ⚠️