1

In hexagonal architecture, domain layer has no dépendency with framework.

Is it possible to use Spring cache in domain layer ?

chupee120
  • 123
  • 1
  • 8

2 Answers2

2

Hexagonal architecture isolates the domain logic from the Infrastructure, such as the database, search engine, message queue, mail delivery, and the cache system. The domain is free of any infrastructure and framework boilerplat. Only Infrastructure Layer must contain the implementation details of Spring Cache. It is achieved via Dependency Inversion Principle by making the class depend on abstractions (interfaces or abstract classes) instead of concrete classes. This means that the depending class has no knowledge about the concrete class that it is going to use, it has no reference to the fully qualified class name of the classes that it depends on. High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.


Let's review several implementations where cache makes sense.
Cache at the Repository Level
You can define repository contract in Domain Layer and the implementation must be done in Infrastructure Layer where you define persistence and Spring Cache details. Domain will not know details about the cache system but will use it thru repository implementation. Every client of your repository will use the cache. enter image description here
Cache at the Application layer
Application Service is about use cases. Implementation cache on this level gives you more control of where and when you want to use a cache. You can define Cahce Manager contract at Application layer and perform implementation details in Infrastructure Layer. Also it can be done like proxy or decorator for your services where you will apply Spring Cache annotations. enter image description here

Eugene
  • 5,269
  • 2
  • 14
  • 22
  • Thanks are application service and use case part of domain layer ? – chupee120 Jun 27 '22 at 19:02
  • 1
    No, Application service is an orchestrator, it orchestrate the steps required to fulfill the commands imposed by the client. While these services shouldn't have "business logic" in them, they can certainly carry out a number of steps required to fulfill an application need. Typically, the Application Service layer will make calls to the Infrastructure Services, Domain Services, and Domain Entities in order to get the job done. Also, service call Repositories to get Domain Objects from DB. See https://stackoverflow.com/questions/2268699/domain-driven-design-domain-service-application-service – Eugene Jun 27 '22 at 20:11
1

Caching is application concept, not a business concept: you could write another application for the same business that would not have cache involved. In an hexagonal architecture, caching should go in the adapter layer, not in the domain layer.

ArwynFr
  • 1,383
  • 7
  • 13