Dependency injection between business layer and presentation layer - java

I am trying to follow clean architecture in my software. I have implemented 3 layers: data layer, business layer and presentation layer.
As far as I understand dependency will follow outside to inside like P->B->D.
But my question is should I do a singleton data layer executor injection into presentation? Doesn't that break this logic?
Or without DI, only create an abstraction between layers I think creates tight coupling.
So referring to some data layer dependency from inside the business layer - doesn't that make the layers tightly coupled?
public class ViewModel<T> extends GenericRouter {
IPresentation ip = new BusinessUseCaseImpl();
public abstract class BusinessUseCase<T extends HashMap> implements IPresentation<T> {
UserRepository urepo = new UserRepository();

In the clean architecture, the inner layers are logic, not infrastructure.
When the business layer instantiates the data layer, it injects any infrastructure dependencies that it requires.
Similarly, when the presentation layer instantiates the business layer, it passes in any infrastructure dependencies that it requires. This is how the business layer gets the infrastructure it needs to pass to the data layer.
And initially, when the application/system instantiates the presentation layer, it passes in the infrastructure that it will need. The humble object pattern should be used to implement these dependencies, because they are the only part of the system that can't be tested independently from infrastructure.

It depends on what you mean by "tight coupling".
Following the 3 layered architecture is ok for the data layer to be a dependency on the business layer and the business layer to be a dependency on the presentation layer.
Instead of injecting a concrete class, you can always define the dependency injection on an Interface. With this, you can always switch the implementation as long as you follow the agreed interface.
However, my experience tells me that you rarely or never do this for a basic and regular 3 layered architecture. You have always a single Service and a single Repository/DAO implementation so having an Interface for each of them is kind of redundant and useless.
I think that the most important thing when you work with 3 layered architecture is to never bypass layers. Examples:
You should never make the presentation layer depend directly on the data layer. Always go through the business layer.
The relation between the layers should be always 1:1. This means you should never make a Controller call a Service that is associated with another Controller.
Not following these rules will for sure make your code incredibly hard to read and understand. Of course, for every rule, there is an exception, but try to stick to them.

Related

Spring Architecture Questions: is Service needed?

I'm new to Spring and I'm creating a REST-Service.
I wonder what the Service-Layer is for (#Service).
Currently I encapsulate my DAOs with that Layer.
So for example my PersonController receives a PUT, calls the PersonService which calls the DAO which finally saves the person in my database.
I also saw some examples in the www. (https://howtodoinjava.com/spring/spring-core/how-to-use-spring-component-repository-service-and-controller-annotations/)
I also have read this question here: Is this a good Spring Architecture (include testing)
Do I even need the Services, if it only calls the DAO like:
public void save(Person p) {
personDAO.save(p);
}
?
I don't really see what the advantage of this is. I create classes which actually do nothing... Or is it just a architecture standard because additional business logic will be in this layer too?
Also... when I have several services like personService, familyService, animalService, etc. and they all have some method signatures that are the same and some which aren't... is it useful to use Interfaces here?
When I create Interfaces like: Saveable, Loadable, Deleteable (does this even make sense?) - how do I use them correctly? Do I create a new Interface for every service that extends the Interfaces I desire? Like a PersonServiceInterface that extends Loadable and Deleteable and I implement it in my PersonService?
Thanks in advance!
If you do not feel the need for a service layer, then chances are high your controllers are performing way more business logic than they should.
adding a service layer in between allows for dedicated tests of pure frontend (controller handle request and response wiring only / services handle the business logic/ repositories persist and query the data).
so rule of thumb - it is much easier to have many services handle fractions of your logic than to stuff everything into your controllers
i am not sure what you are trying to solve with the interfaces you introduce - i do not think it makes sense to re-invent the Repository interface on top of your services. If your services only forward to repositories directly then there is no use in having them anyway.

Mixing DAO and service calls

Let's say we have some layer above service layer, with web controllers for example. Service layer is in turn above DAO/Repo layer. In the upper layer the service calls are used alongside repo calls. It breaks the layering of the application to some extent, but should we really bother about wrapping repo methods like findAll() into service methods. I don't think so. Are there any drawbacks that might cause a lot of pain because of such design? Transactional issues?
I would turn your question around and say - why not have a service layer for such a method? Is it such a pain to wrap a DAO method like:
public class PersonService {
...
private PersonDao personDao;
...
public List<Person> findAll() {
return personDao.findAll();
}
...
}
Client data
What if you don't want to send back the data entity that represents a Person to your controller? You could map the data in the service layer to an Object that only clients are dependent on.
Coupling
You are also coupling your layers. The controller layer should only depend on the service layer and the service layer should only depend on the DAO layer.
Transactions
All transactions should be handled at the service layer (as a service method may call multiple DAO methods).
Business Logic
All business logic should be in your service layer. Therefore, you should never bypass such logic by calling a DAO directly.
I know, for a method like findAll, it seems pointless but I think the point about layer coupling defeats that argument.
Yes it can be a pain if some developer used to call DAO layer code directly from other layers i.e. other than Service layer or whatever architecture you are following for this as a solution:
Use maven dependencies create 4-5 different modules for your project and mention the dependencies in pom.xml so that no calls will be made from any other incorrect layer.
For making it more clear:-
If you want to access layer 3 only from layer 4 just add one dependency entry in layer 3 for 4 and as no other modules have access to layer 3 they can't call code from it.
You definitely get hundred of example for doing this.

Using Services and DAOs in spring mvc controller

I'm building a web application that primarily constitutes of CRUD operations of data from back end/database. There are instances where in I have to write business logic(I'm sure we will have more business logic built as we go deeper in to development). Currently for each UI screen I'm creating I create a model class,Service class, DAO class, a controller(it's servlet essentially) and bunch of jsp pages. In most cases the service class just calls the methods from DAO to pass in model objects. Essentially we use model classes to map data from UI screens. Hence the controller will have the model objects populated when a form is submitted. I have started using service classes to keep a separation layer from web layer to DAO layer. But at times I feel that the service class is just adding unnecessary level of API calls, I would think that I could just inject the DAO in to Controller and complete the task faster. I want to use the service class only when there is additional business logic to be performed. If you have to design an application what factors do you consider using controller->DAO vs controller->Service->DAO control flow?
DAOs are more granular and deal with one specific entity. Services provide macro level functionalities and can end up using more than one DAO. Typically, Services are used for defining transaction boundaries to gain atomicity. In other words, if you end up updating multiple tables using multiple DAOs, defining transaction boundary at service will help in either committing or rollbacking all the changes done to DB.
In your design, since you are primarily doing CRUD for various entities, it may seem that services are not adding much value. However, think of web-based front end as one way of updating data. Usage of services will allow you to expose same capabilities as a web-service later to other forms of client like third party integrators, etc.
So, in summary, your design seems to be in line with conventional practices. If you feel that you can combine multiple services into one based on some common theme such that it can reduce the overhead of code, then, you should go ahead and do it. At the end of day, ultimate goal is to create maintainable code which no one is afraid to change when need arises.
In Pro-Spring-3 book they mentioned below line, for controller with JPA2
Once the EntityManagerFactory had been properly configured, injecting it into your service layer
classes is very simple.
and they are using the same class as service and repository as in below:
package com.apress.prospring3.ch10.service.jpa;
// Import statements omitted
#Service("jpaContactService")
#Repository
#Transactional
public class ContactServiceImpl implements ContactService {
private Log log = LogFactory.getLog(ContactServiceImpl.class);
#PersistenceContext
private EntityManager em;
// Other code omitted
}
but in case you are going to use spring-data CRUDRepository or JPARepository then your DAO will be Interface and you have to make service layer to handle your code
I'd reference my answer here
The long and short of it is the advantage of using a Service layer is it gives you room to move in the future if you want to do anything with Spring Security and roles etc. It allows you to handle transactions more atomically and Spring itself has really nice annotations for this.
Use a service class when dealing with more than one aggregate root.
Inject repositories (aka a dao that returns a collection) or dao's directly into controller, no need for an extra layer/class to do a basic get.
Only use service classes where necessary, otherwise you have twice as much code as required.
You can make repository generic, and annoatoate with #Transactional(propagation = Propagation.REQUIRED) which enforces a transaction is present, but won't create a new one if already present. So if you later use multple repositoes in one service class method, you will only have the one transaction.

May Service annotated classes contain SQL/HQL in spring framework?

i examine lots of samples but i didn't find an adequate solution for this.
Some documents say "Ideally your business logic layer shouldn’t know there is a database. It shouldn’t know about connection strings or SQL."
I found some samples which locate the business logic to #Service annotated classes but they use SQL/HQL in #Service methods.
What should be the ideal usage? If we want to change database or persistence technology should we change only #Repository annotated classes or both of them?
I prefer putting all persistence-related stuff (i.e. queries, and everything dealing with JDBC, JPA or Hibernate) in a DAO layer, and have the service layer rely on this DAO layer for persistence-related stuff.
But the main goal is not to be able to change the persistence technology without affecting the service layer. Although that could be possible if you switch from Hibernate to JPA, for example, it wouldn't be if you switch from JPA to JDBC, for example. The reasons are that
JPA automatically persists all the changes made to entities without any need for update database queries , whereas JDBC doesn't, and thus needs additional update queries
JPA lazy-loads association between entities, whereas JDBC doesn't
...
So changing the persistence technology will affect the service layer, even if all the persistence stuff is isolated in DAOs.
The main advantages of this decoupling, IMHO are
clearer responsibilities for each class. It avois mixing persistence-related code with business logic code.
testability: you can easily test your service layer by mocking the DAO layer. You can easily test the DAO layer because all it does is executing queries over the database.
In your service methods you shouldn't use any SQL/HQL syntax or any database work. All of them should be in DAO layer which are annotated as #Repository. You should just call them from your service methods. In this way, you can easily change your db in future. Otherwise, it would have too much burden
Ideally your business logic deals with or consists of objects that model the domain. It shouldn't be aware of the issues of persistence etc. . That's what O/R-Mapper like hibernate are all about. The business logic demands required objects, based on domain attributes (like Employee name, last month's revenue ...).
The persistence layer should be able to translate the business demands into SQL/HQL/Service calls or whatever the used technology requires. Therefore the business logic layer only changes when the business logic changes.
That would be the goal in an ideal world, but in reality it won't work for non-trivial problems. You can't avoid some degree of coupling. But as #JB Nizet said, it pays off to reduce the coupling to a reasonable amount. Using TDD and adhering to OO principles like SRP will help you get there.

Domain layer and DAO layer with DDD approach

According to many programers, DAO layer can be bypassed when using JPA.
While using DDD approach, domain layer composes of infrastructure region (containing external resources like repositories implementations) and domain region (with entities, needed value objects and repositories interfaces and services etc...).
Thus, if DOA layer is skipped, should the infrastructure region be part of domain layer within a package called 'infrastructure' for instance ?
If infrastructure part should be moved in a separated layer (separated project to get things cleaner), are circular dependencies acceptable between domain layer and infrastrure layer? Indeed, entities and interface repositories must be shared.
Otherwise, should I separate entities and repositories interfaces from Domain layer in order to be considered as an independent thing shared by domain and infrastructure ?
What is the good practice ?
In DDD, the data access objects (DAOs) are Repositories. There's no "DAO layer", persistence is part of the Infrastructure layer.
As you mentioned, the contracts (interfaces) of Repositories are defined in the Domain layer while their concrete implementation resides in the Infrastructure layer.
There's no need for the Domain layer to reference the Infrastructure since entities are supposed to be pure domain objects, unaware of how they are persisted, transferred to other systems, and so on.
"In other words, each of the layers uses an abstract interface that
represents it's infrastructure needs. It does not know what
infrastructure it will be using. It simply states it's needs through
an abstract interface and expects the infrastructure to implement that
interface and supply the required functionality."
http://www.artima.com/weblogs/viewpost.jsp?thread=35139
A DAO layer and a infrastructure region/domain region are not the same things. DAO layers are used when implementing the infrastructure/domain regions.
Your programmers are correct, JPA is the DAO layer. You still need the infrastructure region and domain regions. They'll just be smaller/differnet then if you had to implement a DAO layer within these two regions.

Categories