DispatcherServlet初始化完成后如何调用方法

时间:2017-07-10 05:40:21

标签: spring spring-mvc spring-boot spring-annotations

如何在

之后调用方法
  

[DispatcherServlet] FrameworkServlet   'org.springframework.web.servlet.DispatcherServlet-1881e0df':   初始化在4859毫秒完成

我正在创建实现ApplicationListener

的Class
@Component
public class ApplicationContextListener implements
    ApplicationListener<ContextStartedEvent> {

  @Override
  public void onApplicationEvent(ContextStartedEvent event) {
    System.out.println("ApplicationContext was initialized or refreshed: "
        + event.getApplicationContext().getDisplayName());
  }
}

但是在Dispatcher Servlet完成之后,onApplicationEvent仍然没有激活。

任何人都知道这有什么问题吗?

2 个答案:

答案 0 :(得分:1)

您需要使用ContextRefreshedEvent。 ContextStartedEvent仅适用于手动启动applicationContext的特定情况。

有关ContextStartedEvent和ContextRefreshedEvent之间区别的更多信息,可以参考此answer

答案 1 :(得分:0)

根据spring文档 ContextStartedEvent 仅适用于 ConfigurableApplicationContext 界面。

使用ConfigurableApplicationContext接口上的start()方法在启动ApplicationContext时发布ContextStartedEvent。这里的“已启动”意味着所有生命周期bean都会收到明确的启动信号。通常,此信号用于在显式停止后重新启动Bean,但它也可用于启动尚未为自动启动配置的组件,例如,尚未在初始化时启动的组件。Spring documentation on Standard and Custom Events

相关问题