Spring 4 REST Quick Start with JavaConfig


How to configure a SPRING MVC REST app is something that might be bugging you? This article tries to help you with some quick rapid side notes on how to get this done and understand some part of what you are trying to do.

Spring has come over strong to the rest space with its now easier configuration of web apps. Almost all xml cam be now written in JavaConfig and annotations that have been provided. Although spring boot is another step ahead of this, It is prudent to understand the mechanics behind all of this in a JavaConfig view point and as well understand how to do REST with JavaConfig. Let’s just understand how to do MVC with java config after which REST will be a piece of Cake

1 — Generate maven webapp archetype

2— Prepare your pom like this

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">



<relativePath/> <!-- lookup parent from repository -->




Packaging war is vital if you want to avoid the embedded container.

3 — Adding a view

Now add a simple index.jsp at the src/main/webapp/ directory, what ever you like.



This is the bare minimum needed to get a spring web app running with java config. The annotations and springs conventions take over rest of the work that used to burden developers. But it is just opinionated and customizable when you want to.

4-Adding the controller

package com.pluralsight.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class HelloController {

@RequestMapping(value = "/greeting")
public String sayHello(Model model) {
model.addAttribute("greeting", "Hello World");

return "hello.jsp";


This is no different than before you have state that this is a @Controller and define a @RequestMapping. But we do have to configure our dispatcher servlet for this to work even though we do not include it in an xml file. Nevertheless this will not work since we have also not defined our applicationContext which is the main settings configuration for our spring app. All of these will now be done with JavaConfig.

5 — Configuring the app

package com.dhis;

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

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

* Created by dehan on 6/5/16.
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext .addServlet("DispatcherServlet",new DispatcherServlet(context));


public AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
return context;

This is the boilerplate needed get things started for this web app. For information all these contexts please check this. Here we have stated our webconfig location as our application context. Also we are activating our dispatcher servlet to act as the mediator for all requests. The add mapping will define what Regex will be accepted as a mapping. So if due to the code segment.


Hence if we call localhost:8080/somewhateverthing.html, the Dispatcher will search for a controller that has the request mapping “/somewhateverthing”.

6 — setting up the view

Next we need to add the relevant jsp page which is a hello.jsp according to the above controller returning

return "hello.jsp";

By default opinion of spring 4 java config, the view resolver will search for a hello.jsp @ “src/main/webapp” [not …+/WEB-INF]. This is springs default viewResolvingMechanism already wired up which can also be further configured. You can see that since we have not defined any prefix or suffix it directs to the root web app dir and finds the exact file name on that default directory.
So put in this hello.jsp in the said location. The controller passes some data to the model variable greeting. If this gets resolved it justifies that everything works.

<h1>CONTROLLER IS WORKING YOOOO!!! ${greeting}</h1>

Now deploy this war and check if everything works @ localhost:8080/greeting.html

7 — Customizing config in your web application

Let’s introduce a custom view resolver to the application so that we are meeting up our experiment app with some best practices.

In the above example we just return the absolute name of the html file to be returned. By bringing a view resolver into the picture we are enforcing a prefix and suffix to what the location and file should look like.

package com.dhis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

* Created by dehan on 6/5/16.
@ComponentScan(basePackages = "com.dhis")
public class WebConfig {

public InternalResourceViewResolver getInternalResource ViewResolver() {
InternalResourceViewResolver resolver = new InternalResource ViewResolver();

return resolver;

This is how we are going to change our src/main/java/com/dhis/ WebConfig.java file. This is how we define our View resolver in JavaConfig.

8 — Defining a RestController

Once all this is done getting this to act as Rest has been made really easy by spring with the RestController. But before going there let’s take a step back and define a model, POJO which is needed to be returned to the user.

This is a Human Model a basic Plain old java class where we will use this model to send the details of a few humans as a json response.

package com.dhis.model;

* Created by dehan on 6/5/16.
public class Human {
private String name;

private int age;

private String gender;

public int getAge() {
return age;

public void setAge(int age) {
this.age = age;

public String getName() {
return name;

public void setName(String name) {
this.name = name;

public String getGender() {
return gender;

public void setGender(String gender) {
this.gender = gender;

Ok now let’s add our first RestController @ src/main/java/com/dhis/ controller/Human.java

package com.dhis.controller;

import com.dhis.model.Human;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

* Created by dehan on 6/5/16.
public class HumanController {
public List<Human> getEvents() {

List<Human> humans = new ArrayList<Human>();
humans.add(new Human("Mark",29,"Male"));
humans.add(new Human("Dehan",24,"Male"));
humans.add(new Human("Philangi",30,"Female"));

return humans;


The beauty of the rest controller is that it takes care of setting up the json view resolver and jackson mapping it to over model etc. All the boilerplate is written for you.

However we have to add a mapping to .json to our dispatcher servlet for this to work so go to src/main/java/WebConfig.java file and add the following as a mapping under the existing *.html mapping.


Now deploy and try out your first ever rest controller @ http://localhost:8080/human.json !

You can find the code for this solution here. This is how the final code structure will look like.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.