没有web.xml,无法启动spring mvc 4应用程序

D.R*_*.R. 1 spring web.xml spring-mvc servlet-3.0

我试图仅使用注释来部署spring mvc 4 没有web.xml文件的Web应用程序@Configuration.我有

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;
}
Run Code Online (Sandbox Code Playgroud)

}

我的WebConfig.java班级看起来像:

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

}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试启动应用程序时,我在日志中看到:

14:49:12.275 [localhost-startStop-1] DEBUG oswcsAnnotationConfigWebApplicationContext - 无法为config location []加载类 - 尝试打包扫描.抛出java.lang.ClassNotFoundException:

如果我尝试添加web.xml文件,则会正常启动.

M. *_*num 7

您使用的方法setConfigLocation在这种情况下是错误的.您应该使用该register方法.

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

然而,为了实现这一点,WebApplicationInitializer我强烈建议使用Spring的一个便利类.在你的情况下,它AbstractAnnotationConfigDispatcherServletInitializer会派上用场.

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"}; 
    }
}
Run Code Online (Sandbox Code Playgroud)