13 Nisan 2021 Salı

Lombok @FieldDefaults Anotasyonu - Üye Alanları Örneğin Private ve Final Yapar

Giriş
Şu satırı dahil ederiz
import lombok.experimental.FieldDefaults;
Açıklaması şöyle
This annotation provides a way to set default modifiers for the fields in a class. You can control the access level of fields and specify whether they should be final. This is particularly useful in Spring-based applications where you might want to establish consistent field-level access control without explicitly declaring it for each field.
Açıklaması şöyle
When you annotate a class with @FieldDefaults, you can specify two key elements:

Access Level: The visibility of the fields, such as PRIVATE, PROTECTED, PACKAGE, or PUBLIC. The default value is PRIVATE.
Final: A Boolean value specifying whether the fields should be final. The default is false.

makeFinal Alanı
Açıklaması şöyle. Yani @Data ile üretilecek setter metodları engelleyebilir
Setting makeFinal = true works well when you are creating immutable classes, but it does limit the functionality of other Lombok annotations like @Setter. In classes annotated with @Data, the makeFinal = true setting will essentially disable the generation of setter methods, because final fields cannot be modified once initialized.
Örnek
Şöyle yaparız
import lombok.Data;
import lombok.experimental.FieldDefaults; import lombok.AccessLevel; @Data @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class SecureBook { String title; String author; int pages; }
Örnek
Elimizde şöyle bir kod olsun
@Slf4j
@RequiredArgsConstructor
@FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE)
public class UserService {
  @NonNull UserDao userDao;
}
Açıklaması şöyle
The @FieldDefaults annotation adds the final and private modifiers to all of the fields. 





Hiç yorum yok:

Yorum Gönder