Spring Configuration from XML to Java not working

I cannot get a simple Spring application to work with 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 {
    }
}

And the controller:

package com.doge.controller;

@RestController
public class HelloController {

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

I always get 404 on "localhost: 8080 / Build" or "localhost: 8080". Nothing is ever recorded or printed, just "INFO: starting the server in 538 ms."

+3
source share
1 answer

There are several options for initializing a Spring web application. The simplest of them is as follows:

public class SpringAnnotationWebInitializer extends AbstractContextLoaderInitializer {

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

}

Other options can be found here: http://www.kubrynski.com/2014/01/understanding-spring-web-initialization.html

0
source

All Articles