In hexagonal architecture, domain layer has no dépendency with framework.
Is it possible to use Spring cache in domain layer ?
In hexagonal architecture, domain layer has no dépendency with framework.
Is it possible to use Spring cache in domain layer ?
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.
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.
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.