【问题标题】:Spring Config from XML to Java not working从 XML 到 Java 的 Spring Config 不起作用
【发布时间】:2014-02-12 18:51:49
【问题描述】:

我似乎无法让简单的 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 毫秒内启动”。

【问题讨论】:

    标签: java spring spring-java-config


    【解决方案1】:

    初始化 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 2017-01-09
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 2012-09-07
      相关资源
      最近更新 更多