服务器starup的监听器和完全加载的所有spring bean

在我的Web应用程序中,我想创建一个Listener,当我的服务器启动并且所有bean都被加载时,它会得到通知。 在那个Listener中,我想调用一个服务方法。 我使用了ServletContextListener 。 它有contextInitialized方法但它在我的情况下不起作用。 它在服务器启动时但在spring bean创建之前就被驱散了。 所以我得到服务类的实例为null。 是否有其他方法来创建Listener。

我将在Spring上下文配置中注册ApplicationListener的实例,该实例侦听ContextRefreshedEvent ,它在应用程序上下文完成初始化或刷新时发出信号。 在此之后,您可以致电您的服务。

您将在下面找到实现此目的所需的ApplicationListener实现(取决于服务)和Spring配置(Java和XML)。 您需要选择特定于您的应用的配置:

基于Java的配置

 @Configuration public class JavaConfig { @Bean public ApplicationListener contextInitFinishListener() { return new ContextInitFinishListener(myService()); } @Bean public MyService myService() { return new MyService(); } } 

XML

       

这是ContextInitFinishListener类的代码:

 import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public class ContextInitFinishListener implements ApplicationListener { private MyService myService; public ContextInitFinishListener(MyService myService) { this.myService = myService; } @Override public void onApplicationEvent(ContextRefreshedEvent event) { //call myService } } 

您可以使用Spring的事件处理 。 您正在寻找的事件可能是ContextRefreshedEvent

是的,您需要在web.xml中添加ContextLoaderListener ,仅当您在加载应用程序时还要加载其他Spring上下文xml文件时,您可以将它们指定为

  contextConfigLocation  /WEB-INF/spring-security.xml   

更多你可以访问此链接可能对您有所帮助。

点击这里