Ryan Aleksander
Ryan Aleksander

Reputation: 433

IllegalStateException: Cannot initialize context because there is already a root application context present

In my application there are 2 initializers: one extends AbstractSecurityWebApplicationInitializer, the other extends AbstractAnnotationConfigDispatcherServletInitializer. When I tried to run the application, I got the an IllegalStateException: Cannot initialize context because there is already a root application context present

If I understand correctly, both the initializers tried to create their own WebApplicationContext. So I tried overriding the createRootApplicationContext() to force it to return null. Although the application did run with no exception, it ran incorrectly. Is there anyway to work around this?

WebInitializer.java

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { WebConfig.class, AppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { RepositoryConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

SecurityWebApplicationInitializer

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;


public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

Upvotes: 1

Views: 1724

Answers (1)

Ryan Aleksander
Ryan Aleksander

Reputation: 433

I found the problem, I'm not supposed to put a constructor in SecurityWebApplicationInitializer. The constructor will create a new ContextLoaderListener. Just remove that and everything works fine.

Upvotes: 2

Related Questions