10 Mart 2020 Salı

SpringBoot @ConditionalOnProperty Anotasyonu

Giriş
Belirtilen property belirtilen değere sahipse bean nesnesini yaratır. Böylece bazı ayarları değiştirerek uygulamayı açarsak davranışı değiştirebiriliz.

havingValue Alanı
name ile belirtilen alan havingValue ile belirttiğimiz değere sahipse bean yaratılır. Burada name ile belirtilen alanın application.properties içinde olduğu varsayılır

matchIfMissing Alanı
true ise name ile belirtilen property yok bean yaratılır

Örnek
Property yoksa bean yaratmak için şöyle yaparız.
@Configuration
public class LoggingConfiguration {
  @Configuration
  @ConditionalOnProperty(name = "logging.enabled", matchIfMissing = true)
  public static class Slf4jConfiguration {

    @Bean
    Logger logger() {
      return LoggerFactory.getLogger("sample");
    }
  }

  @Bean
  @ConditionalOnMissingBean
  Logger logger() {
    return new NOPLoggerFactory().getLogger("sample");
  }
}

name/value Alanı
application.properties dosyasındaki alanı belirtir.

Örnek
Eğer hiç bir havingValue değeri tanımlamazsak şöyle yaparız
@Configuration
@PropertySource("classpath:config/service/application.properties")
public class ApplicationConfig {
  @Bean
  @ConditionalOnProperty("client.one.host")
  public ServiceOneClient serviceClient(@Value("${client.one.host}") String host)) {
    return new ClientOneImpl(String.format("%s:%d", host, 80));
  }

  @Bean
  @ConditionalOnProperty("client.two.host")
  public ServiceTwoClient serviceClient(@Value("${client.two.host}") String host)) {
    return new ClientTwoImpl(String.format("%s:%d", host, 80));
  }
}
Örnek
havingValue ile transaction desteğini açıp kapatmak isteylim. Elimizde şöyle bir kod olsun.
// assuming this property is stored in Spring application properties file
@ConditionalOnProperty(name = "turnOffTransactions", havingValue = "true")) 
@Bean   
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionInterceptor transactionInterceptor(
         /* default bean would be injected here */
         TransactionAttributeSource transactionAttributeSource
) {
    TransactionInterceptor interceptor = new NoOpTransactionInterceptor();
    interceptor.setTransactionAttributeSource(transactionAttributeSource);
    return interceptor;
}
Şöyle yaparız. Böylece Spring transaction yaratmaz.
public class NoOpTransactionInterceptor extends TransactionInterceptor {

    @Override
    protected Object invokeWithinTransaction(
        Method method, 
        Class<?> targetClass, 
        InvocationCallback invocation
    ) throws Throwable {
        // Simply invoke the original unwrapped code
        return invocation.proceedWithInvocation();
    }
}
Örnek
application.properties dosyasında satır şöyle olsun.
admin.enabled=false
Şöyle yaparız.
@Configuration
@ConditionalOnProperty(name = "admin.enabled", havingValue=true)
public class AdminControllersConfiguration {

  @Bean 
  public AdminControllerFromModuleApi1 adminController() {
    return new AdminControllerFromModuleApi1();
  }
}
Örnek
Şöyle yaparız.
@Service
@ConditionalOnProperty(value = "polling.enabled", havingValue = "true")
public class MessageQueueService {

  @Scheduled(fixedDelay = INTERVAL_MS)
  public void execute() {
    ...
  }
}

Hiç yorum yok:

Yorum Gönder