7 Nisan 2019 Pazar

SpringContext PropertySourcesPlaceholderConfigurer Sınıfı

Giriş
Bu sınıf normal Spring ile kullanılır. Açıklaması şöyle
Besides the convenient methods of getting properties into Spring – annotations and the XML namespace – the property configuration bean can also be defined and registered manually. Working with the PropertySourcesPlaceholderConfigurer gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.
Bu sınıfı XML içinden kullanmak için şöyle yaparız.
<context:property-placeholder location="classpath:foo.properties" />
Bu sınıf ile property dosyaları okunur. Daha sonra bu konfigürasyon ayarlarına @Value anotasyonu ile erişilebilir.

- Eğer bu sınıf sınıfı kullanmak istemiyorsak okunacak property dosyasını belirtmek için @PropertySource veya @PropertySources anotasyonu kullanılabilir.

- Bu sınıfın bir bean olmasını sağlamak gerekir. Dolayısıyla genellikle @Configuration anotasyonu sınıf içinde kullanılır.

- Eğer SpringBoot kullanıyorsak @EnableConfigurationProperties,@ConfigurationProperties anotasyonlarını kullanmak yeterli

constructor
Şöyle yaparız.
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
  return new PropertySourcesPlaceholderConfigurer();
}
setProperties metodu
Normal Spring ile Yaml dosyasını okumak için şöyle yaparız.
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
  PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = 
    new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  yaml.setResources(new ClassPathResource("default.yml"));
  propertySourcesPlaceholderConfigurer.setProperties(yaml.getObject());
  return propertySourcesPlaceholderConfigurer;
}

Hiç yorum yok:

Yorum Gönder