Spring Boot layer architecture - spring-boot

I am implementing a REST service with Spring Boot and I have an architectural doubt:
I have my #RestController (controller layer) where I check and take the request parameters of my service.
I have a #Service (business layer) where I get some information from other REST services and apply some logic to return it to the controller.
My question is, where is the best place or layer to write the logic to implement the call to the other REST Services and get the objects I need from them?
I am thinking to create another layer, where I provide, through dependency injection, the information to the #Service, is this ok? Is there a better way to do it? Which stereotype annotation would fit in these classes?

I like the dependency inversion principle.
1) Create an interface with the expected baheviour.
2) Create implementation of it as a service, which maps to external dependency.
3) Inject the interface dependency in your business layer and use it.

Related

What is DDD's Aggregate in SpringBoot MVC?

Suppose I've a bunch of microservices, each written on SpringBoot MVC (REST, Controller, Service, etc..)
Can anybody explain what is DDD's Aggregate in SpringBoot MVC? is it a controller? Or is it a specific microservice which is a root for some other microservices?
In other words, is aggregate something within a service with a controller's endpoint as a root? or is aggregate a sub-set of microservices with a particular SpringBoot application/service as an entry point to them?
It is neither a controller nor specific microservice.
It is a cluster of the domain objects that can be treated as a single unit (e.g. Order and its order line) (see this) which is retrieved , saved and searched by the repository.
The spring framework also provides an more specialised #Component called #Repository to represent the repository concepts (quoted from its javadoc) :
Indicates that an annotated class is a "Repository", originally
defined by Domain-Driven Design (Evans, 2003) as "a mechanism for
encapsulating storage, retrieval, and search behavior which emulates a
collection of objects".
Teams implementing traditional Java EE
patterns such as "Data Access Object" may also apply this stereotype
to DAO classes, though care should be taken to understand the
distinction between Data Access Object and DDD-style repositories
before doing so. This annotation is a general-purpose stereotype and
individual teams may narrow their semantics and use as appropriate.
As we use repository to save JPA #Entity or MongoDB #Document to the underlying datastore , so DDD aggregate is more align to them
Two things here.
Spring MVC is a boundary layer to translate between HTTP and internals of the app. The internals are where all the DDD happens, not the boundary itself
Spring Boot is for bootstrapping an application with all the common tools and making a runnable deployment unit.
So, in case of DDD an HTTP request comes to Spring MVC layer, there a domain request is instantiated and passed to domain core for execution. Domain response then comes back and is translated into HTTP response by Spring MVC layer.

Is it appropriate to make /service classes #RestController's

I understand from documentation the distinction between entity and service creation. I'm tempted to simply decorate my services with #RestController/#RequestMapping/#[http-method]Mapping in the same way that /web/rest/resources/* are decorated to expose new rest api methods... maybe using "/api/srv/" to distinguish service-level api resources? It seems to work... when I do it the decorated service methods show up in swagger, etc. I guess I'm just looking for a sanity check that I'm not violating framework convention or misunderstanding the intended use of /service classes.
This really comes down to separation of responsibility. You can expose any class as #RestController no matter it is real Controller or a Service or even a Dao.
However, most of the time, we want each layer to do its own thing.
Controller layer handles the http request/response(request param/body, response code/body etc...) and dispatch to different Service layer methods.
Service layer takes care of real business logic and make calls to the DAO layer to retrieve data needed for business logic calculation.
Dao layer eventually has the responsibility access database with query/hibernate/jpa specifics.
As you can see, each layer is trying to do its own thing and isolate the dependencies from other layers. Like controller layer handles http related stuff so that other layers do not have to carry Servlet dependencies. Same thing for DAO, so other layers need not know any detail about data persistence.
As for swagger, it just analyze your code and annotations and expose whatever in the controller layer. :)
All in all, IMHO, it is still recommended to annotate your real Controller classes with #RestController and let your Service handle the real business.

No "new" objects for Java Spring and how to convert legacy application to "Spring" concept

I have just started learning Java Spring and the concept of Dependency Injection (DI) and Inversion of Control (IoC).
I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
The container manages the dependencies between classes and the lifecycle/scope of the object.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?
I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
That is not quite right. Not all objects, but those you have the cotainer told to resolve, are retrieved from the container. In general you use the #Component annotation to mark which of your objects should the container know of. Besides #Component there are other annotations which do in principle the same, but allow a more finegrained semantics, e.g. #Repository annotation, which is at its base #Component and put #Target, #Retention, #Documented on top.
The container manages the dependencies between classes and the lifecycle/scope of the object.
Yes. The container does the wiring up for you, i.e. resolving dependencies annotated with #Ressource, #Autowired or #Inject depending on which annotation you prefer.
During the lifecycle there are possible events, which allow usage of lifecycle callbacks.
Also: You could determine the bean scope.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
The fundamental principle is, that you delegate the creation of objects of a certain kind to the container. Separation of creation and consumption of objects allows greater flexibility and in consequence better testability of your application.
Besides the "components" of your application, there are e.g. the typical containers like ArrayList or HashMap, upon which you use the new-operator as before.
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?
From what was said above, it should be "simple":
1) Go through each class file and look for its dependencies
2) Refactor those out and put #Component on top of the class
Special case: 3rd party objects, where you do not have access to the source. Then you have to wrap its construction yourself into a factory e.g. with #Bean.
3) Add the missing dependencies via #Autowired (the spring specific annotation for marking dependencies)
4) Refactor components of the service layer with #Service annotationinstead of #Component.
5) Refactor the data access layer, instead of using #Component, you can use #Repository.
This should give you a base to work with.

how to use spring 3.0 without service?

I am using spring 3.0 with annotation which i am creating dao interface , then dao implementation class,
then creating service interface and then creating service implementation class.
and using object of service implementation into controller. this process is too lengthy.
can i use only dao class and directly use it in controller?
#service
#controller
public class MyController { ... }
You can but you really really really shouldn't. If you have any plans of putting this code into production, then you need to keep your layers well defined. This is because each layer has a different responsibility.
Your DAO layer is responsible for all database access. It doesn't care what object you want, what you want to do with it, and when you want it done. It only cares about how it's done.
Your Service layer is responsible for what you want to do to your objects. It contains all of your business logic, convenience methods and may use multiple DAO's inside a single service. Your service layer is where you handle your database transactions as well.
Your controller layer is responsible for how you want to show your data to the user. It only contains services and minimal logic concerned with how to display the data returned by your service layer.
I think there are 2 distinct questions being asked here :
Is it really necessary to have all three layers : web layer, service layer, and DAO ?
and :
Do Spring beans necessarily need to implement and interface and to bve (auto)wired by interface rather thant concrete class ?
The answer to both is the same : it is not a necessity, but it is strongly recommended for anything other thant trivial projects.
For the first question, yes it is better so separate concerns in different layers. However I must admint that my controllers sometimes access the DAOs directly for simple read-only tasks in some projects. Sometimes the service layer seems like too much when all it does is to map the DAO methods. However I always use a service layer for transactional business logic that actually modifies the data.
For the second question : Spring can, without problem, instantiate and inject beans that don't implement any interface. However you will start to have problems if you use more advanced stuff linked to aspect-oriented programming, the most common being the #Transactional annotation. In this case Spring has to create proxies to your objects, and it is all simpler to create proxies of interfaces. Ohterwise it has to manipulate bytecode and it introduces limitations.
Perhaps more importantly, "programming to an interface" is a good practice regardless if you are using Spring or not, or even Java or anothrer language. A simple google search will bring up many good articles on this, or SO questions such as this one.
So again, while you can live well without both things in the short term, both will make your life much better in the long term.

Domain Driven Programming Using Spring

I have a question on DDD & Spring. I always design my application around anemic domain model and service taking care of business logic/persistence.
Assume you have a spring managed persistence/respository service for a Domain object e.g. Book. If I have to expose a save() method on book then i will need repository bean inside my domain or i will have to look up the context for the repository bean. Which is exactly opposite of Dependency Injection.
Now, If I have repository id injected into domain and domain object is cached ( clustered cache) and then on deserialization it will not have the injected repository service as spring containers will be different.
I might be wrong but if someone can explain me how this scenario will work, it would be of great help
I think that the "facade" of your application should use a Repository (or other infrastructure service) to save the "book". The book should not save it-self, this is responsibility of the Repository.
If you need to make any infrastructure operation (for example, search the database) from a Domain Entity, then you should gain access to this Repository by looking up the context (and getting coupled to Spring as a result) or injecting the Repository through Dependency Injection in the Entity.
The problem is that the "instantiation" of the Entity is not responsibility of Spring but of the Persistence Provider, so Spring cannot handle this injection. What to do?
Well, there are several ways (none of them very "beautyful") to do this:
Through AOP: you can instrument the code with Aspect Oriented Framework (like AspectJ) configuring the system to inject whatever dependency in the Entity in the instantiation moment.
Through a Hibernate interceptor: if your Persistence Provider is Hibernate, it offers you a hook to place interceptors in certain points of the life cycle of the Entities. You can configure an interceptor that looks-up the spring context to inject dependencies in the instantiation of every Entity.
Maybe the easiest way is to implement a little and static "serviceLocator" coupled with spring that looks-up services asked by the Entities when they need them. This service locator is just a layer to avoid your entities to get coupled to Spring.
I think that a "save" method (save in a DB, in example) doesn't belong to the domain object... Does the book "save" itself? Or is the repository saving it?...

Resources