D.R.
D.R.

Reputation: 437

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 o.s.w.c.s.AnnotationConfigWebApplicationContext - 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.

Upvotes: 1

Views: 4022

Answers (1)

M. Deinum
M. Deinum

Reputation: 124516

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

Upvotes: 8

Related Questions