17 Ocak 2021 Pazar

SpringBoot @ConstructorBinding Anotasyonu - Properties Dosyası Okuma

Giriş
Şu satırı dahil ederiz.
import org.springframework.boot.context.properties.ConstructorBinding;
Açıklaması şöyle
The annotations, @ConstructorBinding and @ConfigurationProperties are the key here. @ConstructorBinding is used to indicate that the properties from the properties or YAML file will need to be read into this object using its constructor and the @ConfigurationProperties annotation indicates the prefix of the property that needs to be read from the YAML or properties file.
Bu anotasyonun işe yaraması için @EnableConfigurationProperties kullanılmalı. Açıklaması şöyle
Furthermore, it's important to emphasize that to use the constructor binding, we need to explicitly enable our configuration class either with @EnableConfigurationProperties or with @ConfigurationPropertiesScan.
Spring boot 3 için açıklama şöyle. Yani constructor tek parametre alıyorsa bu anotasyon artık gerekli değil.
In @ConfigurationProperties, you don’t need to use the @ConstructorBinding annotation if the @ConfigurationProperties class has single parametarized constructor. If you have more than one constructor, you’ll still need to use @ConstructorBinding to tell Spring Boot which one to use.
Örnek
Şöyle yaparız
@ConfigurationProperties(prefix = "mail.credentials")
@ConstructorBinding
public class ImmutableCredentials {

  private final String authMethod;
  private final String username;
  private final String password;

  public ImmutableCredentials(String authMethod, String username, String password) {
    this.authMethod = authMethod;
    this.username = username;
    this.password = password;
  }
  ...
}

Hiç yorum yok:

Yorum Gönder