3

我似乎无法让简单的 Spring 应用程序与 JavaConfig 一起使用。

public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {

    private static final Logger logger = Logger.getLogger(WebApp.class);

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[0];
    }

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

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        logger.debug("onStartup");
        super.onStartup(servletContext);//MUST HAVE
        servletContext.setInitParameter("defaultHtmlEscape", "true");
    }

    @Configuration
    @EnableWebMvc
    @ComponentScan("com.doge.controller")
    public static class WebAppConfig extends WebMvcConfigurerAdapter {
    }
}

和控制器:

package com.doge.controller;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String sayHello() {
        System.out.println("something");
        return "index";
    }
}

我总是在“localhost:8080/Build”或“localhost:8080”上得到 404。没有任何内容被记录或打印,只是“信息:服务器在 538 毫秒内启动”。

4

1 回答 1

0

初始化 Spring Web 应用程序的选项很少。最简单的如下:

public class SpringAnnotationWebInitializer extends AbstractContextLoaderInitializer {

  @Override
  protected WebApplicationContext createRootApplicationContext() {
    AnnotationConfigWebApplicationContext applicationContext =
      new AnnotationConfigWebApplicationContext();
    applicationContext.register(WebAppConfig.class);
    return applicationContext;
  }

}

其他选项可以在这里找到:http ://www.kubrynski.com/2014/01/understanding-spring-web-initialization.html

于 2014-02-12T10:51:49.013 回答