3

I'm in the situation where I have a Domain Model that is clean. By clean I mean it's just a collection of private properties and getter and setters. I guess that's what's ment by the Anemic Data Model.

This model is interchangeable with other applications (can be shared with other application code) without pulling in extra dependencies.

This model needs to be serialized to different data formats. For this I can use a wide range of annotations that greatly simplify my life.

Only they pull in an extra set of dependencies in all the projects that will share the domain model. I've read it's not advised to clutter the domain model for such reasons and I could possibly land in a Jar Hell.

I could write a wrapper that is annotated and pass in the domain model in the constructor and copy all the properties over to the annotated model. This way I can happily use annotations while keeping a clean Domain Model that will not enforce any extra dependencies.

This is not specifically about serializing your data model but about adding extra functionality (for example through annotations) in your Domain Model that enforces new dependencies.

How do you handle such use cases what's a safe way to handle this without having to fear Jar Hell ?

4

1 回答 1

2

您只需在编译时使用注释。如果注释类在运行时不可用,它们将根本不存在。

例如,如果客户端代码在域模型类上调用 AnnotatedElement.getAnnotations() 并且编译它的注释在类路径中不可用,则不会返回它们。

如果你使用 maven,你应该声明带有可选范围的注解依赖项。客户端中不会包含可选依赖项。因此,它们仅在客户端声明它们时才可用。

例如:

如果 Proj-A 对 Proj-B 具有可选依赖项 ( ?-> )

 Proj-A ?-> Proj-B 

并且 Proj-X 将 Proj-A 引用为编译依赖项,它不会获得可选的依赖项 Proj-B。

 Proj-X -> Proj-A 

因为传递依赖解析以可选依赖结束。

期望您在名为的 jar 文件中有以下注释annotations.jar

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ARuntimeAnnotation {

}

并且您在 a 中包含以下模型类model.jar

@ARuntimeAnnotation
public class Model {

}

并且model.jar依赖于,annotations.jar因为它需要它来编译。

<depdendency>
       <groupId>someGroup</groupId>
       <artifactId>annotations</artifactId>
       <scope>optional</scope>
 </dependency>

如果这个依赖是可选的,它不会自动成为一个人的传递依赖,它只依赖于model.jar.

现在一个客户想要使用这个Model类。因此它依赖于model.jar.

 <depdendency>
       <groupId>someGroup</groupId>
       <artifactId>model</artifactId>
 </dependency>

如果客户端还想查看注解ARuntimeAnnotation,它还必须包含 annotations.jar 作为依赖项,因为它是可选的。

如果客户端不包含对 annotations.jar 的依赖项,则以下调用将返回一个空数组:

 Model.class.getAnnotations(); // will be empty if the annotations.jar is not available at runtime
于 2013-08-20T07:14:22.297 回答