How to use Spring cache in hexagonal architecture? - java

In hexagonal architecture, domain layer has no dépendency with framework.
Is it possible to use Spring cache in domain layer ?

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.

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.

Related

Spring Boot Redis Architectural Design

I would like to ask for some advice regarding the system design for the application I am currently working at. We have a story feature similar to instagram and as a back-end language we are using Java Spring and I have just implemented a Redis cache.
The current layers are like this:
Controller -> Service -> Repository ( Jpa Interface) -> Domain
We will be implementing some caching for a lot of data ( like the user stories of users ).
From a Java architectural point of view does it make sense to add a DAO layer between the service and repository layers where the data source ( aka cache or actual database ) will be chosen. Also does it make sense to actually create a "cache domain" that is a data structure that represents the domain object but is specifically created to be stored in the cache ( a bit like a dto, but for example for a user story I could have a field that shows earliest story element remove time so I know when I can remove certain entries).
The recommended approach is to have caching defined in front of service layer (admittedly, technically there's no restriction in using cache in b/w Service and Repository either), this way your data flow will look like following
Controller -> ServiceCache -> Service -> Repository ( Jpa Interface) -> Domain
The ServiceCache layer (the "cache domain") contract must confirm to Service layer interface. In fact, both ServiceImpl and ServiceCache will implement same (Service) layer interfaces. All methods in ServiceCache should be simple delegate to ServiceImpl layer. This way you can transparently replace Service beans injected in Controllers with that of ServiceCache (say by using spring #Qualifier). You do not have to have to have all ServiceCache built this way, go incrementally as you add caching capabilities to your beans.
The ServiceCache should enable spring cache abstraction, this is more or less de-facto standard for spring applications. This way all caching work is managed by spring itself and you don't have to deal with low level caching constructs by yourself. You should add appropriate hooks in you application to ensure proper eviction and re-population of cache as per your business/technical rules (say using create/update events in service/persistence layer). This can be accomplished using #CachePut, #CacheEvict annotated methods in ServiceCache layer which shall be invoked appropriately by your application specific hooks responsible for updating/deleting cache objects.
Spring cache further abstracts actual cache technology and give you freedom to switch them as may be appropriate without any change in your caching code/logic (e.g. use in memory caffine cache for unit tests and redis OR ehhcache for production). I'll strongly recommend to understand all options available from spring cache and use them effectively for cachce management. Following articles are good start -
A Guide To Caching in Spring
Spring Cache Abstraction
Hope it helps!!

Technical architecture : Service layer or not?

we have a platform composed of few applications.
We have to develop an API which must factorize all interaction to a database.
In this API, we will too have a version of the database in XML format.
The XML format will be used just by one application.
Our application are developped in a classic architectural : dao - service layer - presentation layer.
The DAO layer will be moved into API. No problem on that point.
In many application, the service layer is just a gateway between presentation & dao layer without specific business code.
So my questions are :
should we create the API with a Service layer for each dao ?
if yes, so keep a service layer in application which call service layer from API ?
should we create a service layer in API which manage the factory (database/XML), but that mean each application has to give an information to choose the dao to select (when just one application has this need) ?
or just create all dao in different packages for database & xml in API, keep factory in the application which has the need, and call dao (database) in all others ?
Need help ! :p
I'm lost...
FYI, we are in Java 1.6 with Spring 3.1.1. JDBC Template in DAO for moment.
We are looking informations about spring data jdbc to replace JDBC Template.
Any suggestion about that can be appreciated ^^
[ No Hibernate - JPA solution ]
Thank you.
[edit 1]
In other word, keep a service layer in application & in the API is a way for me to have an abstraction layer. If we have to modify the database structure, maybe we don't have to edit all applications if we can make some changes directly in the service layer of API too.
Imagine 3 possibilities :
service layer in API with factory to choose which dao to use (xml/database)
just dao in API
service layer in API for database & specific layer in API for XML
What solution do you choose ?
[edit 2]
Is it interesting to create an unique class to call the API ? like in a Facade design Pattern.
Use the Service Layer for what is meant to do: provide real world services, by using one ore more DAOs per service offered (and other stuff like managing transactions, sanitizing Strings and other things like that).
If you (together with a more experienced coworker) think you don't need this service layer, then do not put it into your architecture. But make sure to create a proof of concept of your architecture (this may contain the implementation of a somewhat complex functionality of the system or part of it) so you can evaluate it later to demonstrate if you really don't need such layer (or if you do).
My understanding is that you need to decouple and reuse the business layer from the presentation layer, having multiple client applications using the same business implementation.
In this case you need to implement the service layer in the API. Some advantages:
You don't need to repeat the service implementation for any client application handling the presentation.
You can easily decouple the database model design from the business. Design patterns (DTO, Facade) and cross cutting concerns may be easily introduced.
A well designed service layer will require a minimum amount of modifications, compared to DAOs holding DB implementation details.
In this API, we will too have a version of the database in XML format. The XML format will be used just by one application.
By providing this implementation via the API more client applications will be able to use it in the future, if needed.
Spring remoting is offering excellent tools for such a design (RMI, HTTP invoker etc)
I don't see any added value in proving an API for DAOs.

Are the roles of a service and a façade similar?

The more I read, the more confused I am.
Note that all the question is related to how service and facades fit on the MVC pattern.
My understanding is that a Facade is not a super-smart object, it is simply a way of exposing a simple interface/api to perform a complex operation (example: perform a 10$ payment, it is a complex operation that involves a number of operations, but such complexity can be handled by a facade which will just call the corresponding object in a particular order...etc...)
Now, a service is a way to perform calls to several DAOs in order to get complex data structures (I am not too sure of this, but it is what I understand so far).
Question then is, what is the difference between a facade and a service? At the end of the day, the facade can perfectly access several DAOs in order to perform a complex operation by providing a simple interface, and a service seems to to something similar.
Same happens with transactions, I understand that a service is the place to start transactions, but I equally feel that they could also be placed on facades, after all, a facade may call several DAOs too.
So which stack would make more sense
controller-facade-dao
controller-service-dao
or maybe
controller-facadade-dao AND sometimes controller-facade-service-dao ??
A service is a way of writing an interface to an external system, such as a LDAP identity store, a payment gateway or an application management interface. It's a conceptual way of looking at the external system as a provider of useful services perhaps with internal behaviours rather than a passive lump to be operated upon.
A facade is a way of wrapping up anything (including a service) to present it nicely to another component. Facades are often used when:
A library or component is complex and your application needs only a subset of it. Your Facade presents the simplified API to the application
You are using several libraries or components and need to unify them, presenting a consolidated API to the application
The library you are using has a complex setup or set of dependencies, and the facade wraps all that up in the context of your application.
The bit that is really confusing is that you can (and often do) create a facade over one or more services. The service is the way that the component actually accesses the resource, and the facade is the bit which simplifies the component (such as configuration of options, connecting, etc).
If you write your own DAO, you probably will create your service just how you need, so writing a facade is an indication you did it wrong. If the DAO is built by a third party, and is more complex than your needs, then you can facade the service.
Now, a service is a way to perform calls to several DAOs in order to get complex data structures (I am not too sure of this, but is is what I understand so far).
I would say that the DAO is a design pattern all its own - see wikipedia.
If we contrast a DAO with a service, we have:
Level of API:
DAO: Fine-grained access to properties
Service: Coarse-grained access to services
Where implementation lies:
DAO: Mainly on the client, but storing data (without behavior) in the database
Service: Mainly on the server
How the interface is invoked
DAO: The client directly binds to the object in the same namespace and JVM
Service: The client is simply a stub for a network, cross-vm or cross-namespace operation
... the facade can perfectly access several DAOs in order to perform a complex operation by providing a simple interface, and a service seems to to something similar.
A facade could wrap up the DAO layer, but I don't really see this happening in a useful way. Most likely you need an API to access the individual properties of the objects, traverse the object graph and similar, and that is precisely what the DAO provides.
Same happens with transactions, I understand that a service is the place to start transactions ...
Absolutely, because the transaction is a service provided by the database and on another component or system
... but I equally feel that they could also be placed on facades, after all, a facade may call several DAOs too.
And in many ways the transaction manager service is a facade onto a much more complex backend implementation, co-ordinating the transaction on the web, application, database and other transaction-aware components. However this is already abstracted away by the transaction service implementation. As far as we, the user, are concerned, there is only the public interface.
This is, in fact, the conceptual point of these design patterns - to provide just the right amount of API to the user, abstracting the complexities of the implementation behind the iron wall of the component interface.
So which stack would make more sense
controller-facade-dao controller-service-dao
or maybe
controller-facadade-dao AND sometimes controller-facade-service-dao ??
The DAO is a kind of service to the database, but really the DAO is a design pattern itself.
If you write your own DAO, you should never need a facade.
Therefore the correct answer is:
controller - dao
Literally, Facade as the name suggests means the front face of the building. The people walking past the road can only see the facade, They do not know anything about what inside it, wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a simpler friendly face.
In software terms, facade hides the complexities of software components behind it by providing a simpler interface, doesn't have the functionality of its own and doesn't restrict the access to the substsyem. Commonly used in Object Oriented Design.
Good examples are SLF4J - It is an api which is a simple facade for logging systems allowing the end-user to plug-in the desired logging system at deployment time.
A service is a public interface that provides access to a unit of functionality and always written to a specification. It needs to support the communication contracts (message-based communication, formats, protocols, security, exceptions, and so on) its different consumers require.
There is process services - encapsulation of business workflows , business logic service - encapsulation of rules/functions, data services - interaction with entities, data access management, infrastructure services- utility functions such as monitoring, logging & security. Services are mostly reusable, unassociated, loosely coupled units of functionality.
They are lot similar but depends on how you look at it.
The difference that I see, Facades are designed inside out. You look
at subsystem and design a facade to provide simpler access. Services
are designed outside in. You look at your customer/clients define a
contract and design the service.
My understanding of the classical GoF Facade pattern is that it's mainly intended to hide a poor design. As a rule of thumb, I would say that one should only need a Facade for legacy code.
I also think that this pattern made its way as a J2EE core pattern (Session Facade) mainly because the EJB spec (at least up to 2.x) inherently resulted in a poor service layer design.
Therefore, my answer to your question would be yes -- a facade is actually a service that hasn't been properly implemented the first time. If you need to hide the complexity from client code, it usually means that you only managed to provide a library, not a service layer; so, in this case, the Facade actually becomes your service layer.
On the other hand (assuming you have a decent domain layer), if you really need to provide the option of spawning complex flows with a single method call (something resembling macros/aliases), this would usually be better placed in the application layer and not in your core domain -- notice that I've switched layering terminology to domain driven design, where there's no "data access" or "service" layer, but "application", "domain", "infrastructure".
The first thing to note is that a design pattern is a description for a common (design) problem with a standard solution. In some cases there are several ways to solve the problem in a way that fits all requirements (f.ex. the Iterator and Singleton patterns have tons of different implementations; f.ex. check the work of Alexandrescu and compare it with the standard GoF solutions) and in some cases there are different patterns with the same (code) solution (f.ex. compare the class diagrams of the Composite and the Decorator patterns in the GoF book).
According to the GoF the purpose of the Facade pattern is to (literal quote):
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
Services have the intention of providing a user with a single higher level interface with a given functionality. That doesn't necessarily make it a facade, because a service is strictly speaking not by definition a unified interface to a set of interfaces in a subsystem.
But we can do better than that
Your question was if the patterns are "similar". If we consider them to be "similar" when pattern A equals B and pattern B equals A, then we should answer 2 questions:
Question 1: is a Service a Facade? A service should definitely expose functionality and is definitely a single interface that exposes this functionality. Functionality is normally decomposed into tiny pieces, so yes, services fit the underlying requirements of a facade. In other words: faced by the problem of exposing the underlying interfaces as a unified "service" interface, the facade pattern fits the requirements and is used to solve the service problem. The answer to this is yes.
Question 2: is a Facade a Service? Services are normally designed as reusable, unassociated, loosely coupled units of functionality. Thinking about communication between components is important for services, because they usually rely on a TCP/IP interface such as SOAP or WCF. This also means that functionality is often rewritten to fit the services paradigm more closely, which adds an implicit driven by performance requirement for the pattern. Facades don't have this extra requirement. In other words: a facade is not a service.
In exact terms, these concepts are closely related, but not the same.
But we can do better
This line of thinking raises the question if a service is an extended version of a facade? It is if a service meets all the requirements of a facade and extends on top of that.
If you read the description by the GoF closely, the answer is yes, that is: if one condition is met: The service has to expose subsystems. In reality, I think this condition normally holds, or you're over-designing your services - though strictly speaking I suppose this is not a hard restriction.
FACADE is a design pattern which solves the problem where there is a need for a unified interface to many interfaces in a subsystem so it defines a higher-level interface that makes the subsystem easier to use.
HOWEVER, A SERVICE provides access to resources or a set of interfaces/objects and may not necessarily simplify such an access. So you can employ the facade pattern to better design your service so you can save the client figuring out how to construct to use it.
Usually these terms are just used in their specific contexts.
'Facade' common usage context: simple API for complex parts of the application (like third-party libs)
'Services' context: unlock and surface the business entities in the system. (SOA, DAO, Security, etc)
You can view patterns as a language that evolves. It never seemed to be perfect end each pattern has it's own history and context. Sometimes classes could be viewed as Services and Facades at the same time, sometimes not.
For example: calling third party API by term 'Service' could be considered as misuse, because of the wrong context.
Before I try to answer, let me clarify something: there are three distinct things in enterprise applications - Facade, Service Layer, and Remote Facade.
Facade - while wrapping the subsystem(s), still is an object and UI (MVC) application usually lives in the same process. Thus, the communication is done in an usual OO manner: calling methods, reading properties, listening to the events.
Service Layer - when the business logic layer becomes mature and too complex for the MVC to interact with it directly, then Service Layer is put between them. Service Layer is an API that MVC uses as a wrapper of the business logic. It is not remote and is not required to use DTO since no wire is involved in the communication.
Remote Facade - (simply, any remote service) this is a hybrid of the Facade and Service Layer. Remote Facade starts existing when you want to expose some kind of wrapper over the system (and we call it Facade) as a distribution boundary. One of the reasons can be to allow several UI (MVC) applications use the same Remote Facade.
-
Comparisons:
Facade vs. Service Layer: they are similar since both they wrap subsystems. Difference is that Service Layer is more oriented on UI (MVC) application needs and exposes functions to simplify working with business logic. On the other hand, Facade is exposing functionality to simplify the business logic, but does not necessarily simplify the communication with UI (MVC) application.
Facade vs. Remote Facade (Service?): definitely different since Remote Facade must use DTOs as communication messages. Remote Facade will need some kind of proxy if you still want to use it as a regular object (properties, events); but the proxy will anyway use DTOs to the real object, i.e. Remote Facade.
-
Possible Flows:
controller-facade-dao - doubtful, but still possible. Facade is not usually used to wrap just DAL. There should be something more mature in addition as a subsystem. But, if the facade is part of the business logic, then yes, this is possible. Still the subsystem must be more emphasized. To me, DAL wrapping is not enough to call it Facade.
controller-service-dao - absolutely possible. Many remote services work directly with database through DAL.
controller-facade-service-dao - maybe, if you treat service as a subsystem.
I would add one more that can make sense:
controller-service [layer]-facade (part of business)-subsystem (e.g. accounting, business on its own)-dao - I'm sure you can translate this.
-
Remember, Service (or remote facade) can exist anywhere in the flow. That is just dictated by your distribution needs.
A service interface typically represents business concerns: perform some operation(s) and/or get some information. It wouldn't be unreasonable for the service provider to implement their service as a facade over internal back-end services - you'd never see this.
Your facade might wrap some general interfaces, which might include service interface(s).
For example, you might have service interface for a bank account (operation: Bank transfers money), and a local API to your local accounting records (I transfer money). You might introduce a facade over with a "move money" operation that uses the bank's service interface and manages your local checkbook as well.
It is the "context" that's matters. Facade and Service are not conflicting.
First I have never heard of "Service" and "Facade" in the context of MVC.
When people talk about Service, it is more about a system or component providing business-meaningful actions to outside world. You may sometimes see "Service" related to "Unit-of-work" (and hence, transaction).
Service is also used in the context of some layering approach of application: we have Service on top of DAO, for which Service will access data through DAO and business logic is put in Service layer, something like that.
Facade is usually used in the context of design pattern, and the focus is about "hiding complicated operations and expose it as a simple operation".
Facade may be or may not be a Service (a operation in Facade may not represent a Unit of work, but it is still a valid facade), similarly, a Service may or may not be a Facade (a Service may not hide any complicated operations but it is still a Service).
Again, it is all about the "context" that matters.
For example, when you are talking about layering of application, it is simply irrational to say "XXX is a facade to access DAO". Similarly, if you are talking about "design approach", it is more reasonable to say "XXX is a facade to multiple back-end" instead calling it a "Service" here (Although XXX is actually a Service).
Yeah, Facade and Service are not entirely unrelated. And some time we implement Service layer as Facade so that client is not bothered about to many details of the service. The more simpler the invocation/interface of a service is the simpler and easier clients code.
The Martin Fowler says...
A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations
So services layer is used at times as Facade.
Ref
Facade and Service Layer has kind of a similarity but both of them has two distinguished meanings. Let me explain this using a simple example.
Imagine we are asked to create new business application. This has a requirement of creating a check-in application but with more value added features and loyalty card features.
Lets say application should support Facebook and Foursquare check-in features if user wish to use. This feature is very much needed because some users are reluctant use several applications doing the same function or get rid of social connectivity.
to get a highlevel idea, refer sample api on the following link https://docs.google.com/file/d/0B3v8S0e-PvVpdWFJOVhqc1d2SHc/edit?usp=sharing
Above check-in API located at ABC facade is an example for usage of Facade.
It has our service API and also facebook and foursqure check-in capabilities based on client's selection. Facebook and foursqure APIs can have specific implementations (SOAP, Restful, etc. ) and security (OAuth etc.) requirements etc.
Satisfying one of these APIs (facebook, foursqure) requirements needs to fulfil different set of tasks. these will be different sub systems with in our check in requirement.
So facade's simplistic usage is to satisfy several sub systems triggered by one simple method
But if we consider our own API which is check-in API located at MngCheckinSvc. This is a service layer API. This is the API that contains our application's check in requirements. This is the API provide public access from your MngCheckinSvc to handle check-in requirement to application.
This will have complex inner behaviors but still most of them will be application specific logic implementations.
This API(MngCheckinSvc.checkin(....)) might access different set of DAOs, Internal APIs, may be other internal services etc. in order to fulfill merchant check-in with in the application.

DDD and application layer

Is the application layer (application services) where I add #Stateful, #Stateless, #WebService etc. in DDD? From the link below this seems to be right.
Second question: I have made a repository class, should all method calls involving repository be wrappen in an application service? Or can I use repository classes directly in let say backing beans in JSF? When and what do I put in the application layer. I don't understand where the EJBs belong in this artitechture.
Application Layer: This layer coordinates the application activity. It doesn't contain any business logic. It does not hold the state of business objects, but it can hold the state of an application task's progress.
http://www.infoq.com/articles/ddd-in-practice
Java EE advocates anemic model, which is the opposite of DDD. If you want DDD, your entities must also perform the business logic, which is contrary to the separation of service layer and entities.
It's supposed that in DDD architecture the Application Layer and all the other layer communicate only with lower layer of the system. For this reason the application service wrapp repositories, but if you are using dependency inyection you can reuse all your repositories along the application service layer
The real work of AppService is to coordinate operations beetwen other service or repositories or inclusive domain services.
In your entities must to be bussiness logic only about your own entities. Always respecting Single Responsibility Principle (http://www.developerfusion.com/article/137636/taking-the-single-responsibility-principle-seriously/).
I hope be helpful

Do aspects substitute repositories?

I started experimenting with Spring Roo just recently. It does a very nice job helping one build a domain model with integrated persistence rather quickly. As it adds persistence functionality in aspects, I started think about the following question:
Roo adds finders (load an instance of a class from the database which meets variable criteria) in an aspect to the actual class/entity. In DDD this is IMHO the responsibility of repositories. Repositories are explicit classes which show up in the design. Of course as an aspect the repository functionality is hidden in an entity and is pretty much invisible.
So here is the question: Is an aspect a real substitute for a explicit repository class? Are there any downsides to the Roo AOP approach?
Adding finders to your domain classes feels more natural from a user's point of view but it mingles your layers. Grails uses the same approach by adding static finder*() save(), ... methods.
Apart from the aestetics it might have practical drawbacks when not used in web application setting:
Your domain classes are now tied to your database. If you transfer these objects to rich clients via RMI or HttpInvoker the client cannot and often may not use the find* methods because there is no session / database connection available on the client.
I generally prefer allowing domain classes to reference service layer interfaces to prevent an anemic domain model (http://martinfowler.com/bliki/AnemicDomainModel.html). This has its own set of drawbacks but at least provides a clear boundary. On the client the concrete implementation behind a service interface can then just proxy all method calls to the server (or just use a synamic proxy with spring remoting or sth similar).
So to answer your question: It might be a substitute but you should be aware of the possible negative consequences which make your domain classes (i.e. your core business logic) less portable between systems.
This depends on how complicated your applications persistence layer is and how much control you have over it. If your application is simple enough to be implemented via JPA, then it all could be handled via Roo aspects. However if you are mapping legacy tables or need advanced DB stuff, then you may find yourself in a situation where Spring-JDBC is the only way out and in these cases a repository/dao model may still be useful.
I consider it logical inconsistent (and a break of layer responsibility) to be mixing two persistence models and so as most of my applications requires such advanced DB constructs I stick strictly with a repository model.
I think adding repository methods to domain objects is bad design. The right place would be static methods in the domain class. But domain objects and their management are two different things that should be separated. I would prefer domain objects and repositories.
I guess the motivation was to achieve something Rails/Grails like with Java.

Categories

Resources