Services and DTOs in Spring Boot applications

Getting into Spring Boot, part 5 Services and DTOs in Spring Boot applications

A robust architecture is the basis for larger applications. Also Spring Boot-Service components and Data-Transfer-objects, to keep the Code maintainable and extensible help.

Company to the topic

Model mapper is a good library for the Mapping, the associated .org-website also has valuable tips.
Model mapper is a good library for the Mapping, the associated .org-website also has valuable tips.(Image: Modelmapper.org)

In the past articles, two basic types of Spring were presented components: the Controller for the processing of Requests and Repositories as a link to the database. These blocks can be used different layers of the map, how they are to be found in the majority of applications: The controllers are part of the presentation layer (Presentation Layer), the Repositories belonging to the Persistence Layer.

A new layer

In the previous examples, the Controller have spoken directly with the Repositories, the Repository was in the Controller Autowired injected, and then in the Repository methods, such as, for example, findAll() called. As the return value of the Controller has get Entity objects from the Repository.

This approach is sufficient for simple applications, in larger projects, but the limits. Due to the direct dependence of the Controller of the Repositories of the data source is not readily replace it. What if the data is to be loaded instead of the one from the database in the future from a Web Service?

Services are located in the Business Layer.

Services are located in the Business Layer.(Image: Dr. Koller)

Actually, the Controller should not have to not have to deal with that part of his area of responsibility. He is responsible for the receipt of the request and the mapping to an appropriate Handler method. From an architectural point of view, it therefore makes sense to establish an additional layer between the Presentation and Persistence, the business layer.

Component-made business logic

The business layer describes the business logic in the Form of Servicesanother type of Component in Spring. This approach has several advantages: A Service is easy to use. It can be used by different controllers or even as part of a REST API function. As is often the case in software development, it is, therefore, the avoidance of fixed dependencies to loose coupling.

Like all components in the Service-component of the Component inherits.

Like all components in the Service-component of the Component inherits.(Image: Dr. Koller)

Services in Spring with the Annotation @Service_ characterized. As well as the already introduced annotations @Repository_ and @Controller_ from inherits the Annotation @Component_. The child annotations, are specialized components, the names of which allow a conclusion on the function. Technically, Spring Boot will find all the components mentioned in the context of the automatic Component Scanning, provided they are included in a suitable package in the Classpath.

Interface vs. implementation

In order to keep independent of the implementation, should Services as a Java-Interfaces described. As an example, here is a small Service to return the full Name of a Person:

public interface PersonService {
public String getFullName(Long id);
}

The implementation of the Interface in the Form of a Java class is @Service annotated. You have to attack now, instead of the controller to the Repository as usual _@Autowired_ integrated:

@Service
public class PersonServiceImpl implements PersonService {
   @Autowired
PersonRepository personRepository;
   @Override
public String getFullName(Long id) {
Person person = personRepository.findById(id).get();
return person.getFirstname() + " " + person.getLastname();
}
}

The Controller uses the Service and by gets it _@Autowired_ injected. Here is to ensure that the Interface Person serviceand not the implementation Person serviceimpl, is used. Spring is looking, then, at the Start of the container according to suitable types and instantiated automatically, the only existing implementation of the Interface.

Through this approach, the implementation if necessary, easily replace the internals of the implementation are hidden from the Client (i.e. the Controller):

@Controller
public class PersonController {
   @Autowired
PersonService personService;
...
}

Often it will be necessary for Services multiple Repositories using a business case process. A little caution is used to hang Together in the term “Service”, because it is in the Spring environment in various. Complete applications are sometimes referred to as a Service.

A good example, REST Services, micro-services environment. These usually include a Service component in the Interior, but the complete Spring application. In our case, the implementation of the business logic is meant by the term only in the Form of a Service component.

Object Transporter

Each of the above layers accesses the underlying layer to exchange data. The Repositories, for example, to provide Entities to the Service. Although it is possible, then to the Controller to pass, but here, too, more elegant approaches exist.

As mentioned above, the Controller should have to do with the nature of the data collection and for this reason no Entities know. Instead, the Controller data needed to be repackaged in a Data Transfer Object (DTO). This is a Special, on the needs of the controller tailored POJO (Plain Old Java Object).

This item is no longer contain, for example, all the attributes of a Person, is enriched but with additional data from a commercial entity. DTOs to decouple the layers from each other and ensure maximum reusability. The hook of the overhead.

In addition to the Creating and Maintaining of the classes of the data to be transferred, for example, a Person Entity in a Person-DTO. You can make either by Hand, using the set methods (tedious and inelegant), or with the help of the Builder Pattern (tedious, but more elegant).

Alternatively, it is also one of the specifically established for this purpose Mapping can be libraries. With the under Apache v2 license published model mapper, for example, to Create the DTO instance, and the transfer of the data looks as follows:

Model mapper model mapper = new model mapper();
PersonDTO personDTO = model mapper.map(person, PersonDTO.class);

This is not just tedious and quite elegant, but another dependency to the project. Still, these two lines of Code to reveal another, more of a cosmetic Problem when working with DTOs: If the Entity is already named Person is assigned this Name for the DTO.

A distinction only because of package names is confusing and error-prone. There is much else to do, other than on terms such as PersonDTO or person entity to Dodge. Not fancy, but the flexibility this minor Blemish justifies all.

(ID:47063652)

Ready to see us in action:

More To Explore

IWanta.tech
Logo
Enable registration in settings - general
Have any project in mind?

Contact us:

small_c_popup.png