4 Haziran 2018 Pazartesi

SpringContext ApplicationListener Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.context.ApplicationListener;
onApplicationEvent metodu - ContextClosedEvent
ContextClosedEvent için açıklama şöyle
ApplicationListener is a Spring Framework interface that allows components to listen for specific application events and respond accordingly. In our case, we will focus on the ContextClosedEvent, which is triggered when the Spring application context is about to be closed during shutdown.
Uygulama kapanırken tetiklenir. Şöyle yaparız.
@Component
public class AppStoppedListener implements ApplicationListener<ContextClosedEvent> {

  @Autowired
  @Qualifier("executorService")
  private ExecutorService executor;

  @Override
  public void onApplicationEvent(ContextClosedEvent event) {
    executor.shutdown();
    try {
      // define how much time to wait for the completion
      if (!executor.awaitTermination(15, TimeUnit.MINUTES)) { 
        List<Runnable> incompleteTask = executor.shutdownNow();
        // do that you want with them
      }
    } catch (InterruptedException e) {
            // handle or log exception
    }
  }
}
onApplicationEvent metodu - ContextRefreshedEvent
Temel (core) event'ler şöyle
ContextRefreshedEvent
ContextStartedEvent
ContextStoppedEvent
ContextClosedEvent 



Spring Boot event'leri şöyle. Ayrıca bir de WebServerInitializedEvent var
ApplicationStartingEvent 
ApplicationEnvironmentPreparedEvent 
ApplicationContextInitializedEvent 
ApplicationPreparedEvent 
ApplicationStartedEvent 
AvailabilityChangeEvent 
ApplicationReadyEvent 
ApplicationFailedEvent 


Uygulama açılırken tetiklenir.
Örnek
Şöyle yaparız.
public class ApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    ...
  }
}
Örnek
Şöyle yaparız.
@Component
public class AppStartedListener implements ApplicationListener<ContextRefreshedEvent> {

  @Autowired
  private UserProfileRepository repository;

  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    for(UserProfileType userProfileType: UserProfileType.values()) {
       UserProfile up = new UserProfile(userProfileType);
       repository.save(up);                
    }      
  }
}
Örnek
spring.jpa.properties.hibernate.ddl-auto parametresini değeri none değilse exception fırlatmak için şöyle yaparız.
@Component
public class YourListner implements ApplicationListener<ContextRefreshedEvent> {

  @Value("${spring.jpa.properties.hibernate.ddl-auto}")
  private String hibernateDdlAuto;


  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {

    if (!"none".equalsIgnoreCase(hibernateDdlAuto))
      throw new MyValidationException();

  }
}

Hiç yorum yok:

Yorum Gönder