IllegalStateException:无法初始化上下文,因为已存在根应用程序上下文

时间:2016-08-07 02:58:33

标签: java spring spring-mvc

在我的应用程序中有2个初始值设定项:一个扩展AbstractSecurityWebApplicationInitializer,另一个扩展AbstractAnnotationConfigDispatcherServletInitializer。当我尝试运行应用程序时,我得到了IllegalStateException: Cannot initialize context because there is already a root application context present

如果我理解正确,两个初始化程序都试图创建自己的WebApplicationContext。所以我尝试重写createRootApplicationContext()以强制它返回null。虽然应用程序确实运行,但没有异常,它运行不正确。无论如何要解决这个问题吗?

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 个答案:

答案 0 :(得分:2)

我发现了问题,我不应该在SecurityWebApplicationInitializer中放置构造函数。构造函数将创建一个新的ContextLoaderListener。只需删除它,一切正常。