3

如何以允许我的代码停止初始化的方式连接到 Spring Application Context 的初始化?

我想编写在所有 bean 完全初始化之后但在 Spring 触发 ContextRefreshedEvent 之前执行的代码,如果我的代码无法完成它需要做的事情,它能够停止初始化。

特别是我想启动 Quartz Schedule 但只有在一切都开始之后并且如果石英无法启动我想停止应用程序。目前我正在使用像这样的 Servlet 上下文侦听器来完成任务。

public class QuartzServletContextListener implements ServletContextListener
{

    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        ServletContext servletContext = sce.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        Scheduler scheduler = applicationContext.getBean(Scheduler.class);
        try
        {
            scheduler.start();
        } catch (SchedulerException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce)
    {

    }
}

servlet 上下文监听器在 spring 上下文加载器监听器之后运行,并且 RuntimeException 停止了 tomcat。

4

0 回答 0