Monday, April 20, 2015

Spring JavaConfig

I recently learned how to use Spring JavaConfig.  Unfortunately at work, we are still using XML-based Spring Configuration.

I wanted to dig into JavaConfig, so I started using it at home on personal development projects.

Just replaced the full contents of the web.xml file with the following:


package com.philiptenn.scholarship.init;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author Philip Tenn
 */
public class Initializer implements WebApplicationInitializer {

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    public void onStartup(ServletContext servletContext)
            throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebAppConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));

        ctx.setServletContext(servletContext);

        Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
                new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }

}


Now, my web.xml file is really skinny ...


  
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         metadata-complete="false">

  <display-name>Spring MVC Application</display-name>

</web-app>


Having such a small XML file, that doesn't even contain a Servlet entry for the Spring MVC DispatcherServlet felt strange, like walking on a tightrope without a safety harness. However, everything seems to be working fine. :-)

No comments:

Post a Comment