在Dropwizard中注册一个事件监听器

时间:2018-01-16 07:40:55

标签: java spring-boot dropwizard event-listener

是否有任何可能的方法在Dropwizard中注册侦听器,相当于Spring Boot中的以下实现:

@EventListener(ApplicationReadyEvent.class)
public void registerMessagingEvents() {
    registerListener1();
    registerListener2();        
}

2 个答案:

答案 0 :(得分:1)

您可以向Dropwizard ServerLifecycleListener添加Environment

通常,这是在Application子类'run()方法中完成的。

例如:

@Override
public void run(YourApplicationConfiguration config, Environment environment) {
  environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() {
    @Override
    public void serverStarted(Server server) {
      // do something
    }
  });

  // ... others
}

虽然“Jetty服务器准备就绪”(这是Dropwizard生命周期事件所指示的)与Spring Boot的ApplicationReadyEvent不完全相同,但它与Dropwizard提供的等效钩子相同,它可能满足您的需求。

更多详情in the docs

答案 1 :(得分:0)

另一种可能的实现方式可能是使用environment.lifecycle().addLifeCycleListener

当您需要访问某些注入的类/实例时,它很有用。 例如:

//In the run method 
    Injector injector = Guice.createInjector(myModule); //existing code

    ...
    // somewhere in the end of the run method
    environment.lifecycle().addLifeCycleListener(
      new ServerLifecycleListener(injector.getInstance(MyService.class)));

//And then implement the listener ServerLifecycleListener class:
private static class ServerLifecycleListener implements LifeCycle.Listener {
private MyService myService;

ServerLifecycleListener(MyService myService) {
  this.myService = myService;
}

@Override
public void lifeCycleStarting(LifeCycle lifeCycle) {
}

@Override
public void lifeCycleStarted(LifeCycle lifeCycle) {
  myService.doSomething();
}

@Override
public void lifeCycleFailure(LifeCycle lifeCycle, Throwable throwable) {
}

@Override
public void lifeCycleStopping(LifeCycle lifeCycle) {
}

@Override
public void lifeCycleStopped(LifeCycle lifeCycle) {
}

}