Pages

Sunday, February 9, 2014

Modern Spring 4 MVC Hello World Tutorial

I was browsing reddit as I am wont to do at pretty much any hour of any day and came across a Spring 4 MVC tutorial. At work I use Spring 4 and was curious what a beginner tutorial would look like. Even though it was a small tutorial I expected to see things like @RestController and JavaConfig. I even hoped to see Gradle, but alas it was all XML configuration and a maven build with even more XML. No wonder people get such a bad impression of Spring and Java. Below I've quickly put together a tutorial using techniques I use working with Spring 4. I'm glossing over some things so if something doesn't make sense just leave a comment. It's super simple and some things are overkill but it's just so you can get a flavor of what working with Java and Spring 4 can really be like.

All the code can be found on it's github repository.

The build file

The most important parts are the repositories section and the dependencies section. The repositories section defines where to find the dependencies of your project designated in the dependencies section. In this case we can get everything from Maven central. The ext section defines some variables used for the specific versions of your dependencies. The buildscript section allows us to add functionality into gradle. In this case we are adding a tomcat plugin so we can launch a tomcat instance directly from the gradle build.


The Configuration

We will be using a completely XML-less configuration. This requires a server that supports servlet 3.0 and above. This means >= Tomcat 7 or >= Jetty 8. Major takeaway is that we will put our controller in the com.hello.controller package so we need to scan that package.


The Controller

Spring 4 introduced a new controller annotation @RestController. This is just a convenience annotation that means the class is an @Controller class and all the methods are @ResponseBody methods. This is a nice addition when building out REST webservices using Spring MVC.


The view

We are using AngularJS to interact with our controller. The way most of the webapps I've been writing lately work is having a Java backend provide a REST webservice to a javascript frontend. There are pros and cons to this approach which can be debated but I've been having fun and been productive using this method.

The Controller Test

Spring has really nice support for testing your controllers as well.



Result

Make sure you have JDK 7 installed and then run it yourself by grabbing the code and from the command line run ./gradlew tomcatRun for OSX/Linux or gradlew.bat tomcatRun if you are on Windows. Gradle should take care of everything else for you.