简体   繁体   中英

can not start spring mvc 4 application without web.xml

I am trying to deploy spring mvc 4 web application without web.xml file using @Configuration annotation only. I have

public class WebAppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext)
        throws ServletException {
    WebApplicationContext context = getContext();
    servletContext.addListener(new ContextLoaderListener(context));
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
            "DispatcherServlet", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("*.html");
}

private AnnotationConfigWebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setConfigLocation("ge.dm.icmc.config.WebConfig");
    return context;
}

}

and my WebConfig.java class looks like :

@Configuration    
@EnableWebMvc     
@ComponentScan(basePackages="ge.dm.icmc")    
public class WebConfig{

}

But when I try to start the application, I see in log :

14:49:12.275 [localhost-startStop-1] DEBUG oswcsAnnotationConfigWebApplicationContext - Could not load class for config location [] - trying package scan. java.lang.ClassNotFoundException:

If I try to add web.xml file, then it is started normally.

You are using the method setConfigLocation which, in this case, is wrong. You should use the register method instead.

private AnnotationConfigWebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(ge.dm.icmc.config.WebConfig.class);
    return context;
}

However instead of implementing the WebApplicationInitializer I strongly suggest using one of the convenience classes of Spring for this. In your case the AbstractAnnotationConfigDispatcherServletInitializer would come in handy.

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    protected Class<?>[] getRootConfigClasses() { return null;}

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

    protected String[] getServletMappings() {
        return new String[] {"*.html"}; 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM