Moving to Spring Boot
The Spring framework has been the de facto standard framework to build a Java application on for some time now. Providing an IoC container and performing dependency injection was just the start. Since it’s initial release in 2002, Spring has expanded and matured, providing developers with familiar, patterns-based abstractions for common components throughout an application’s layers. As Spring grew, the configuration became more and more unwieldy and the framework became known as one that involved a fair amount of effort to set up and get going, and even the most trivial of projects came with a fair amount of boilerplate configuration. There was not an easy place to start. Maven filled this gap in the early days, pushing the community toward the concepts of convention over configuration and dependency management, and through the use of project archetypes, but the same problem eventually cropped up – repetitive, difficult-to-manage configuration.
With the first release of Rails in 2005, the developer community saw what was possible in terms of a developer-friendly framework that all but eliminated the perceived shortcomings of frameworks like Spring. Frameworks like Rails came to be known as Rapid Application Development (RAD) frameworks. These frameworks shared many of the same characteristics – a well-defined convention, opinionated default configurations, scaffolding tools used to quickly create pre-configured components. In 2009, the Spring developers responded to the trend of RAD frameworks with the release of Spring Roo. Spring Roo was never billed as an attempt to replace Spring, only enhance it by eliminating the shortcomings of vanilla Spring. Spring Roo provided a well-defined convention and scaffolding tools, but was driven by AspectJ and relied on a significant amount of code generation to eliminate boilerplate code. This led to difficulty troubleshooting configuration problems, and a steeper learning curve for developers new to Java and Spring.
Enter Spring Boot…
In 2014, the Spring development team released a next-generation take on Spring named Spring Boot. Spring Boot provides many of the same RAD-like features of frameworks like Rails, and goes a step further than Roo by eliminating cumbersome XML-based configuration and the mystery of generated code. This is accomplished through the use of auto-configuration classes. Each Spring Boot module is packaged with a default configuration – the boilerplate code developers used to be responsible for creating. These auto-configuration classes provide the opinionated configuration familiar to users of other RAD frameworks, and that follows the basic best practices familiar to users of traditional Spring. In the next few sections, we’ll get a new project up and running from scratch and see auto-configuration in action.
Creating A New Project
A newer feature of the Spring Boot project is the Spring Initializr, a website (http://start.spring.io) that allows a developer to choose a starting point for their application with a 1 page form the concludes with a ‘Generate Project’ button and a download of the shell project. Below, you can find the steps I used to configured a basic project:
These choices produced the following project structure:
This project can be built and run, but without at least one controller we’ll have no page to display other than a default error page. Let’s create a controller and test out the app.
Create a file in the root package of the project – in my case it’s /src/main/java/com/spr/demo/SampleController:
[code language=”java”]
package demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by justin on 2/15/15.
*/
@Controller
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
}
[/code]
Next, start the server from the root of your project using the pre-configured Gradle script provided to us by Spring Initializr.
[code language=”bash”]
Justins-MacBook-Pro:demo justin$ gradle bootRun
[/code]
You can see in the console output that the app started an already-configured Tomcat server running on port 8080. If we browse to http://localhost:8080 in a browser, we should see the following:
That’s a full-fledged Spring app with a wired controller and a base configuration. Counting every line of code, that’s only 30 lines of code!
Adding A Template
You may remember that we chose a templating library (Thymeleaf) as part of our initial configuration on the Spring Initializr page. Let’s add a page template to our example to show how simple it is to set that up as well. To do this, we’ll have to create the template itself and change our controller slightly. In the earlier screenshot of our project, you’ll see we have a ‘templates’ directory in our ‘src/main/resources’ directory. Create a file there named ‘hello.html’:
/src/main/resources/hello.html:
[code language=”html”]
HELLO
[/code]
You can see we’ve added a placeholder for a string named ‘message’ that we’ll supply from our controller.
Next, let’s update our controller to populate the ‘message’ element:
/src/main/java/demo/SampleController.java:
[code language=”java”]
package demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by justin on 2/15/15.
*/
@Controller
public class SampleController {
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("message", "HELLO WORLD!");
return "hello";
}
}
[/code]
Now, when we run our app, we should see a different result – one that builds a page using the template we just created:
Who’s Behind The Curtain?
You can see we’ve created a full Spring app with a basic configuration, configured a controller, and started using a template engine to render our pages. If there is no generated code driving this, where is the configuration coming from?
If we take a closer look at the console output from the server starting you can see several references to a class named ‘org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration’. This is where the magic is happening. Let’s take a look at the source on Github (https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java). Browsing through this source, we can see references to familiar bean configurations, the paths to pre-configured property file locations, the base configuration to enable Spring MVC, and much more.
Continued Reading
The Spring Boot docs contain great resources for getting started. The ‘Getting Started’ section provides a nice foundation for those new to the tool. http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started
While the Spring Boot docs contain a lot of valuable information, several of the examples fall a bit short of what we commonly see at clients. Last year, I wrote a 5 part series that expands on the Getting Started guides provided by Spring. http://justinrodenbostel.com/2014/04/08/beyond-the-examples/. This explores some common problems that Spring easily solves: nested form binding, security integration, internationalization, and more.