25 Nisan 2018 Çarşamba

SpringContext ConfigurableApplicationContext Arayüzü

Giriş
Şu satırı dahil ederiz.
import org.springframework.context.ConfigurableApplicationContext;
Açıklaması şöyle. ApplicationContext arayüzünden kalıtır.
When you use an application context, i.e. get beans from it you only use it as an ApplicationContext but when you manage its life cycle (initialization and destruction) you use methods from ConfigurableApplicationContext
constructor
Şöyle yaparız.
@SpringBootApplication
@EnableDiscoveryClient
public class Application {

  public static void main(String[] args) {
    
    ConfigurableApplicationContext context =
      new SpringApplicationBuilder(Application.class)
        .properties("spring.config.name:application,db-config")
        .build().run(args);

    ConfigurableEnvironment environment = context.getEnvironment();
    
  } 
}
close metodu
Servis açılırken hata olursa uygulamayı kapatmak için şöyle yaparız.
@Service
public class MyService {

  @Autowired
  ApplicationContext context;

  @PreDestroy
  public void cleanUp() throws Exception {
    ((ConfigurableApplicationContext)context).close();
    }
}
Örnek
Şöyle yaparız.
@SpringBootApplication
@ComponentScan(basePackages = "lk.tradeportal")
@EnableWebMvc
@ImportResource(locations = "classpath:tradeportal-servlet-config.xml")
public class TRADEPORTALStarter extends SpringBootServletInitializer {


  private static ConfigurableApplicationContext context;

  public static void main(String[] args) {
    
    SpringApplication application = new SpringApplication(TRADEPORTALStarter.class);
    context = application.run(args);
    application.setRegisterShutdownHook(true);
  }

  @PreDestroy
  private static void closeAppContext(){
    context.close();
  }
  ...
}
getEnvironment metodu
Şöyle yaparız.
ConfigurableEnvironment environment = context.getEnvironment();

Hiç yorum yok:

Yorum Gönder