Introduction to Spring Boot, part 10 project Lombok – code minimization with annotations
In this post of Spring Boot series, we introduce you to the project Lombok. It has nothing to do with the Framework, but works perfectly and has the same objective: to get away from the inflated source code, to lean maintainable projects.
Company to the topic
The Project Lombok aims to be unnecessary and bloated Boilerplate Code einzudampfen.
In Java, it does not access the Member variables of a class from the outside directly. It would contradict the principle of encapsulation. This implies that the variables of a class will be hidden from other classes and methods – get and set available.
The internal state of a class is the user’s nothing, he uses the provided interface. Sounds useful, but it also has a disadvantage: there is a lot to be written to get – and set-methods. In the case of data objects with a lot of variables that is a lot of boring work.
Dialog to Generate the Setter and Getter in the Spring-Tool-Suite.
(Image: Koller / Spring)
This one does not have to, luckily enough, in long Hand. The major development environments such as Eclipse, Spring Tool Suite (STS) and IntelliJ IDEA enable you to Generate the Setter and Getter. In the STS you can find the Feature in the menu Source > Generate Getters and Setters.
After the call to the Option, the desired variables in a Dialog and then select the methods produce. This is in all cases better than to write the methods themselves, but not optimal: The class is bloated with “Boilerplate”Code, so geschwätzigem and repetitive Code.
This complicates the Code reader understanding, and he urged all: it Is, perhaps, but somewhere, something to do with the Variable before it is returned? In addition, it must be called for newly added variables, the generation again. That’s got to go any more elegant?
Lombok set up
The Lombok Installer searches for existing IDEs.
(Image: Koller / Lombock)
The Project Lombok, an Annotation-based preprocessor that takes care of this and a whole series of similar problems and harmonizes very well with Spring Boot. Lombok is downloaded from the Homepage of the project as a Jar-File and – in the case of existing Java runtime environment – double-click on the file to start.
The opening of the Installer to add searches for matching IDEs and adds the Lombok support. The search is not successful, you can specify the location of the IDE manually. A project that aims to use Lombok, you must also add the Lombok Jar. In the POM of a Spring Boot application, the following dependency is listed:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Thus, Lombok, is ready to use.
It’s a kind of Magic
All the information for the code generation for Lombok to be done with the help of annotations. For the production of the Get and Set methods for member variables that are in the annotations @Getter and @Setter:
import lombok.Getter;
import lombok.Setter;@Getter
@Setter
public class Person { private String firstname;
private String lastname;
private String email;
}
The generated methods in the Outline View.
(Image: Koller / Spring)
The generated Code for the get and set method, you don’t see in the source code. It is not inserted, when you Compile the Bytecode. The class remains clean and lean. These are still available in the STS in the Outline View, check. Here you will find methods on how to getFirstname() or setLastname().
The generated methods can be used in a normal way, as if they were in the source code available. Also, the Code-Completion to find the methods and, as always, offers the Complete name. But Lombok can do far more than just Generate the get – and set-methods. With the Annotation @ToString it is a useful toString()Method is generated that includes all of the member variables of the class.
The output for the above-defined Person-object, for example, looks as follows:
Person(firstname=max, lastname=mustermann, email=max@mustermann.de)
Annotation @Equal sandy hashCode generated methods equals() and hashcode() based on the member variables. Only if all the variables of the two objects have the same content, it provides the equals()Method to return true.
Commercial construction for Advanced
To Create constructors, the library offers the same three variations: @NoArgsConstructor creates a constructor that accepts no parameters, i.e., Person(). @AllArgsConstructor in contrast, all of the variables in the parameter list required, so here is a Person(String, String, String).
With @RequiredArgsConstructor a constructor to create and contains only the necessary variables. The uninitialized variables, either, with the final (so-called blank-finals) or with the Lombok Annotation @NonNull are marked.
In the following example, a constructor is generated, the firstname (due to @NonNull), and email (final) as a Parameter expected. The final marked lastname is not “blank” because he is initialized with a value of:
@Data
@RequiredArgsConstructor
public class Person { @NonNull
private String firstname;
final private String lastname = "Mustermann";
final private String email;
}
Constructors with many parameters will eventually be unwieldy. A popular Alternative is to use the Builder Pattern, in which the creation of instances of a separate class is entrusted. Their methods carry the name of the Variable that you set, so here, for example, email(). Each of the methods of this class returns the constructed object, so that the next method on the resulting object can call.
Objects with many variables can be so elegant build. And here, too, Lombok provides good services: The Annotation @Builder in the Person class Builder, obtained by a call to the method builder() on the Person class, creates a Person. The person Builder contains the methods firstname(), lastname(), email() and build(). The following example demonstrates how to use:
Person person = Person.builder()
.firstname("Max")
.lastname("Mustermann")
.email("Max@Mustermann.de")
.build();
Logging with the Simple Logging Facade
Finally, be aware of the possibility of Lombok a Logger instance to create. This is done by the Annotation of the corresponding class @Slf4j:
@Slf4j
@Controller
public class PersonController { // ...
}
Internally, this creates a Variable named log to the logger factory:
public class PersonController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(PersonController.class);
}
Also, this Variable does not look natural in their own source code, but in the Outline View. It can be used as usual:
log.info(person.toString());
On Lombok, are the ghosts. And Yes, there are legitimate arguments against the tool. Above all, the fact that all the project members need to install the extension in the IDE. Nevertheless, it was and Lombok is simply a Revolution.
The project saves a lot of work and embellished and streamlined the Code a lot easier. In Conjunction with the slim Spring Boot is relatively close to magic. Fortunately, each remains to decide whether he wants to be enchanted.
(ID:47299205)