簡體   English   中英

在ServletContextListener上獲取Spring應用程序上下文

[英]Get spring application context on a ServletContextListener

我正在嘗試在ServletContextListener上獲取spring應用程序上下文。 我正在使用帶有注釋配置的Spring。 使用此代碼,我得到“ context null”。 我做錯了什么?

@WebListener
public class Initializer implements ServletContextListener
{   
    public void contextInitialized(ServletContextEvent event)
    {
        System.out.println("context " + WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()));
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce)
    {
    }
}

謝謝

解決此問題的關鍵是刪除@WebListener注釋,並在WebAppInitializer重寫onStartup以確保在Initializer之前加載了ContextLoaderListener

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
.
.
.
    @Override
    public void onStartup(ServletContext container) throws ServletException
    {
        super.onStartup(container);
        container.addListener(Initializer.class);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM