49
loading...
This website collects cookies to deliver better user experience
@Override
, @NotNull
, or @Autowired
in Spring. This annotations helps to the class to keep it super clean and easy to understand, we are going to see some examples later in this tutorial.@Getter
, @Setter
and @RequiredArgsConstructor
.@Getter
and @Setter
are the more used annotations from Lombok, its objective is to create all the getter and setter methods of the specified fields inside a class, this annotations are very useful when we are creating POJOs, some examples are the ones that we create for entities or data transfer objects (DTOs). Imagine that we have a class called User, this is an entity class, of wourse we want to have the normal fields for this class, like id, email or password, well that could be something like this:public class User {
private Long id;
private String email;
private String password;
}
public class User {
private Long id;
private String email;
private String password;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
public void setPassword(String password) {
this.password = password;
}
public Long getPassword() {
return this.password;
}
}
@Getter
and @Setter
:@Getter
@Setter
public class User {
private Long id;
private String email;
private String password;
}
@RequiredArgsContructor
. So, again, remember that we are using Spring Boot, so you want to use dependency injection, for sure, using @Autowired
, but you know that there are three ways of how to use @Autowired
. The first one and less recommended is using @Autowired
at the top of a field, this is not recomendded because sometimes this can lead to a SOLID violation. So you use the @Autowired
at the top of a setter when the fields are optional or at the top of the constructor when the fields are required to be injected into the class in order to create a correct functionality.public class UserService {
private final UserRepository userRepository;
}
public class UserService {
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
@Autowired
annotation to inject the field, but now imagine that you use more than one final field (but be careful, not to much fields there to not violate SOLID). We again have more boilerplate code, here Lombok comes to the rescue. We introduce the use of @RequiredArgsConstructor
.@RequiredArgsContructor
public class UserService {
private final UserRepository userRepository;
}
@NoArgsContructor
annotation too, you can find more information here.