Monday, 29 September 2014

Spring Javaconfig Minimal REST Api

This post shows you how to create a minimal REST API in Spring using Java Config (no xml) and maven.

Checkout the code: https://github.com/sparso/spring-javaconfig-examples (look at spring-barebones-javaconfig).

Main Components


It's helpful to have some background on the components that we'll be setting up:

Web Application: The term for a collection of servlets packaged in a war file.
ServletContext: Defines methods to talk to the servlet container (eg Tomcat).
ApplicationContext: Defines methods to access Spring Beans etc.
WebApplicationContext: Extends the above, adds a getServletContext() method.
AnnotationConfigApplicationContext: implementation of the above which accepts annotated classes as input rather than XML.
ContextLoaderListener: Creates the application context. Ties the lifecycle of the ApplicationContext to the lifecycle of the ServletContext.
DispatcherServlet: Takes an incoming request, delegates handling of it to a controller.

Maven


The following is set up in the pom.xml:

spring-framework-bom: Sets version numbers of spring modules so we don't have to.
spring-core, spring-webmvc, spring-web: Minimal dependencies for a REST API.
javax.servlet-api: So we can deploy our module in Tomcat.
maven-war-plugin: Build the war and set failOnMissingWebXml to false.
WebApplicationInitializer

You implement this interface in order to configure the ServletContext programatically.



Option 1: Implement it yourself

The following code shows you how to bootstrap the container yourself. It:

  • Creates the root ApplicationContext (where spring beans live)
  • Attaches a ContextLoaderListener to it (connecting it to the servlet lifecycle)
  • Creates a DispatcherServlet to router HTTP requests to your app.
  • Adds your Java Config classes to each step.


Option 2: Use an AbstractAnnotationConfigDispatcherServletInitializer

This gets rid of most of the boilerplate code:


Context Configuration


Here's my context configuration, documentation in the comments:


REST Controller


Finally here's the controller: