7 Nisan 2020 Salı

SpringContext @Value Anotasyonu - Tek Bir Değişkeni Okuma

Giriş
Açıklaması şöyle. application.properties, ortam değişkeni, JVM parametresi gibi bir değeri değişkene atayabilmeyi sağlar.
@Value annotation is used to assign a value to a property. It is only used to assign a value for a simple type property,for example, primitive types, in a bean class.in this way, IOC container reads the value of a key from resource bundle and initializes a simple property with that value.
Bu Anotasyon Constructor Parametresi veya Metod Parametresi veya Üye Alan Üzerinde Kullanılabilir
Açıklaması şöyle.
This annotation is used at the field, constructor parameter, and method parameter levels. The @Value  annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowired annotation tells Spring to inject an object into another when it loads your application context, you can also use the @Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and ${...} placeholders.
@ConfigurationProperties İle Farkı
Açıklaması şöyle. Tek bir değişken yerine bir sınıfı POJO tüm olarak okumak istersek @ConfigurationProperties anotasyonu kullanılır.
Your two main choices for injecting configuration are using either @Value on individual properties or @ConfigurationProperties on a javabean configuration object.

Which one you use comes down to preference. Personally I prefer using a configuration object.

Using @ConfigurationProperties allows you to use JSR-303 bean validation.
You can also write your own custom validation in the setter of your javabean if you desire.
You can annotate config beans from non-spring projects, which allows you to write libraries that are easily configured but don’t depend on spring.
You can generate IDE meta-data from the objects that may make your development process smoother.
Kullanılan String
Eğer sadece application.properties'teki bir değeri çekmek istersek şöyle yaparız. Dolar karakteri ve süslü parantezler içine değişken ismini yazmak gerekir.
@Value("${...}")
Static Üye Alan
@Value static üye alan ile çalışmıyor. Şu kod işe yaramaz. Çözümü ise static üye alan için setter() metod yazmak.
@Value("${tenantdb.driver.classname}")
static String tenantDbDriverClassname;
Varsayılan (Default) Değer
@Value Anotasyonu Varsayılan (Default) Değer Okuma yazısına taşıdım

Dolar Kareteri ve Hash Karakteri
Bu anotasyon "${...}" veya "#{...}" şeklinde kullanılabiliyor. Açıklaması şöyle.
${...} is the property placeholder syntax. It can only be used to dereference properties.

#{...} is SpEL syntax, which is far more capable and complex. It can also handle property placeholders, and a lot more besides.

Both are valid, and neither is deprecated.
SpEL için @Value Anotasyonu - Conditional Değer Okuma yazısına bakabilirsiniz

1. application.properties Dosyası Örnekleri
application.properties dosyasındaki değerin otomatik olarak değişkene atanmasını sağlar.

@Value Anotasyonu - Array Okuma yazısına taşıdım
@Value Anotasyonu - List Okuma yazısına taşıdım
@Value Anotasyonu - Map Okuma yazısına taşıdım

Örnek - Boolean Okuma
Şöyle yaparız.
@Value("${app.settings.value1:false}")
private boolean value1;
Örnek - Integer Okuma
application.properties şöyle olsun
my.prop.for.func=25
Değeri String değil ama Integer olarak okumak için şöyle yaparız.
@Value("${my.prop.for.func}")
private Integer myPropForFunc; // Needs to be an object and not a primitive data type.

Örnek - String Okuma
Dosya şöyle olsun.
profile.name=myname
Şöyle yaparız.
@Component    
public class SampleClass() implements Runnable{
  @Value("${profile.name}")
  private String name;
  ...
}
Varsayılan değer atamak istersek şöyle yaparız.
@Value("${profile.name:'samplename'}")
Örnek - String Okuma
Şöyle yaparız.
@Value("#{mysql.databaseName}")
private String databaseName;

2. yml Dosyası Örnekleri
Örnek
yml dosyası şöyle olsun.
spring:
  url: localhost
email:
  from: something@gmail.com
app:
  uuid: 3848348j34jk2dne9
Şöyle yaparız. Burada nesnenin constructor metoduna parametreler geçiliyor.
@Component
public class FooA {
  private final String url;

  public FooA(@Value("${spring.url}") String url) {
    this.url = url
  }
}

@Component
public class FooB {
  private final String from;

  public FooA(@Value("${email.from}") String from) {
    this.from = from
  }
}

@Component
public class FooC {
  private final String uuid;

  public FooA(@Value("${app.uuid}") String uuid) {
    this.uuid = uuid
  }
}
3. JVM Parametreleri Örnekleri
SpEL kullanılıyor.
 
4. Shell Parametreleri Örnekleri
Linux'ta export=abs şeklindeki kabuk parametrelerini okumak için kullanılır.

Örnek
Şöyle yaparız.
@Value("#{systemEnvironment['COMPONENT_PARAM_CORS']}")
private String COMPONENT_PARAM_CORS;

Hiç yorum yok:

Yorum Gönder