Sarief Sarief - 1 month ago 5x
Java Question

Spring jpa entity and dynamic dispatching

I have entity Animal. It has two children: Dog and Cat. Animal can makeVoice(), but Cats and Dogs do it differently.

Now here is question, with Hibernate I would retrieve instance of Dog, inside method makeVoice() for Dog I would call HumanService, but it is Spring bean, singleton. How should I design around this? Injecting/Autowiring HumanService seems like poluting Cat/Dog, but this has to be dynamically resolved. I can't think of a way to design this this resolution outside. Is there such way?


If your animals call services, your design seem to be domain-driven but not fully. If you have a DDD, I would not call it HumanService because of Service suffix. I would imagine rather than a dog communicates directly with an human.

I think that you should try to reason by service layers or by communication between domain objects, not a mix of them. Of course, in a DDD you can have services but when it is relevant, not for communication between two objects of the domain.

About mixing spring beans and JPA entities, it looks like indeed a little awkward, not on the logic but on the fact that you use two different libraries to weave behaviors on the same class.
JPA doesn't use Spring to instantiate entities, so you should use tricks to do both. If you can avoid to use Spring in entities without adding big overhead to add logic, I think your design could be cleaner. Otherwise, use tricks.

If mixing both annoy you, don't use DDD but use a design by services : DogService with a method with a dog as parameter communicates with HumanService