1

I am trying to get the spring application context on a ServletContextListener. I am using Spring with annotation configuration. Using this code i get "context null". What I am doing wrong?

@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)
    {
    }
}

Thanks

2
  • 1
    Your ordering of the listeners is wrong. The ContextLoaderListener should be executed before this listener. Commented Sep 20, 2017 at 10:21
  • It worked for me, thanks Commented Sep 20, 2017 at 11:25

1 Answer 1

2

The key for fix the problem has been delete the annotation @WebListener and on WebAppInitializer override onStartup to ensure that the ContextLoaderListener is loaded before Initializer

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
.
.
.
    @Override
    public void onStartup(ServletContext container) throws ServletException
    {
        super.onStartup(container);
        container.addListener(Initializer.class);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.