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

后端 未结 3 907
情话喂你
情话喂你 2020-12-30 02:21

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 clas

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 03:08

    I think the decision comes down to 'lifecycle', and impedance mismatch between lifecycles.

    Lifecycle: Every piece of data, whether its source code, a database row, a compiled class, an object, has a lifecycle associated with it. When does it come into existence and when is it garbage collected?

    Suppose I put Hibernate annotations on a Java class. Seems like a reasonable idea, especially if I am creating a new database from scratch and am confident that only this one application will ever connect to it - the lifecycles of my classes, the database schema and the ORM mapping are naturally in sync.

    Now suppose I want to use that same class in an API and give it to some third party to consume. The Hibernate annotations leak into my API. This happens because the lifecycle of that class and the database are not the same thing. So we end up using mapping tools to translate between layers of beans in a system.

    I try to think about lifecycles and that annotations that can cause lifecycle mismatches should be avoided. Some annotations are relatively harmless in this respect, and some are a hidden danger.

    Examples of bad annotations: ORM mapping, database configuration, hard coded config for items that may vary between deployment environments, validations that may vary depending on context.

    Examples of harmless annotations: REST endpoint definitions, JSON/XML serialization, validations that always apply.

提交回复
热议问题