So, I've noticed that I definitely have a tendency to pattern my Spring/Hibernate stack objects like this:
- Foo controller makes a call to "FooService"
- FooService calls FooRepository.getById() method to get some Foos.
- FooRepository makes some Hibernate calls to load Foo objects.
- FooService does some interactions with the Foos. It may use a related TransactionalFooService to handle things that need to be done together in a transaction.
- FooService asks FooRepository to save the Foos.
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:
- It's annoying to get at other services and objects from a Foo. It's not a Spring bean, and it was loaded by Hibernate.
- It's annoying to get a Foo to do several somethings transactionally.
- It's hard to decide whether Foo should be responsible for choosing when to save itself. If you call foo.setName(), should foo persist the change? Should it wait until you call foo.save()? Should foo.save() just invoke FooRepository.save(this)?
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.
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…