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

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 04:20:46

问题


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);
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/38810475/illegalstateexception-cannot-initialize-context-because-there-is-already-a-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!