春季和贫血领域模型 [英] Spring and the anemic domain model

查看:75
本文介绍了春季和贫血领域模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我注意到我确实倾向于对Spring/Hibernate堆栈对象进行如下模式设置:

So, I've noticed that I definitely have a tendency to pattern my Spring/Hibernate stack objects like this:

  • Foo控制器调用"FooService"
  • FooService调用FooRepository.getById()方法来获取一些Foos.
  • FooRepository进行一些Hibernate调用以加载Foo对象.
  • FooService与Foos进行了一些交互.它可以使用相关的TransactionalFooService来处理需要在事务中一起完成的事情.
  • FooService要求FooRepository保存Foos.

这里的问题是,Foos没有任何真正的逻辑.例如,如果每次Foo过期时都需要发送电子邮件,则不会调用Foo.expire().有一个对FooService.expireFoo(fooId)的调用.这是出于多种原因:

The problem here is that the Foos don't have any real logic. For example, if an email needs to be sent every time a Foo expires, there's not a call to Foo.expire(). There's a call to FooService.expireFoo(fooId). This is for a variety of reasons:

  • 从Foo获取其他服务和对象很烦人.它不是Spring bean,而是由Hibernate加载的.
  • 让Foo进行事务性事务很烦人.
  • 很难决定Foo是否应该负责选择何时保存自己.如果调用foo.setName(),foo是否应该保留更改?它应该等到您调用foo.save()吗? foo.save()是否应该仅调用FooRepository.save(this)?

因此,由于种种原因,我的Spring域对象基本上是带有某些验证逻辑的美化结构.也许没关系.也许Web服务可以作为过程代码.也许随着新功能的编写,创建以新方式处理相同旧对象的新服务是可以接受的.

So for these sorts of reasons, my Spring domain objects tend to be basically glorified structs with some validation logic. Maybe this is okay. Maybe web services are okay as procedural code. Maybe as new features get written, it's acceptable to create new services that deal with the same old objects in new ways.

但是我想摆脱这种设计,我想知道Spring还能用其他什么方法吗?您是否使用花哨的技巧(例如加载时编织)来对抗它(我对此不太满意)?你还有别的把戏吗?您认为程序上还可以吗?

But I'd like to escape from this sort of design, and I'm wondering what other Spring uses do about it? Do you combat it with fancy tricks like load-time weaving (which I'm not that comfortable with)? Do you have some other trick? Do you think procedural is fine?

推荐答案

您可以让Spring使用AOP将服务注入到Hibernate实例化实例中.您还可以使用拦截器让Hibernate做到这一点.

You can get Spring to inject your services into your Hibernate instantiated instances, using AOP. You can also get Hibernate to do the same, using Interceptors.

请参见 http://www.jblewitt.com/blog/?p=129

关于让Foo进行事务性事务很烦人",我希望您的服务实现会知道/关心事务,如果您现在在域模型中使用服务接口,那现在应该不太烦人.

Regarding "It's annoying to get a Foo to do several somethings transactionally", I would expect your service implementations would know/care about the transactions, and if you're now using the service interfaces within your domain model, that should now be not quite so annoying.

我怀疑决定何时保存域模型取决于它是什么以及您在做什么.

I suspect that deciding when a domain model should be saved is dependent upon what it is and what you're doing with it.

FWIW,我倾向于产生相同类型的贫血结构,但是我到了那里,现在我知道有可能以更明智的方式做到这一点.

FWIW I have a tendency to produce just the same sort of anemic structures, but I'm getting there, now I know it's possible to do it a more sensible way.

这篇关于春季和贫血领域模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆