Spring Boot: Getting Started (again) Building A Web App
In the last several years, rapid web application frameworks have been most developers first choice when starting a new project. Rails and Grails have taken the concept of convention over configuration to extremes, eliminating boilerplate code, and allowing developers to create web applications more quickly than ever. The latest incarnation of Spring and its related tools go far in emulating this kind of productivity. Spring Boot and its related starter projects make creating a Spring application possible with just a few lines of code. With Spring Boot recently hitting its 1.0 release, and Spring 4 having just been released in December, its an exciting time to get reacquainted with an old stand-by framework and tool set. The Getting Started projects at Spring.io serve their purpose extremely well, but as they are only intended to get a project up and running, they leave much to be discovered. The individual tutorials are great, but I had a hard time finding something that put it all together into an app similar to what would be required in the real world. Here, in a series of posts, I hope to share some of my experiences to date working on a project using Spring Boot and Spring 4.
Here are the topics I hope to cover in each part:
Part 1: Getting Started (again): Build A Web App With Spring Boot
Part 2: Adding Views Using Thymeleaf
Part 3: Form Binding
Part 4: Locale Support
Part 5: Spring Security
As the latest in a long line of enhancements to the Spring framework aimed at eliminating boilerplate code and decreasing the time spent by developers setting up a new project, Spring Boot serves its purpose well. In this installment, I’ll walk through getting a project off the ground, rehashing much of what is covered in the first Spring-Boot starter guide on the Spring.io site. This will serve as the basis for upcoming installments. In this series, I’ll be using Java 1.7, Gradle 1.11, and Spring Boot 1.0.1.
Setting Up
There are Spring Boot starter versions of several different projects: web projects, data projects, integration projects, etc. Here we’ll be starting with the Spring Boot web project.
The first step is configuring your project’s directory structure. Spring Boot, whether you’re using Gradle or Maven, both follow the classic convention for directory naming and source structure. Create an example project using the structure below, substituting values in square brackets with your own:
[project-name]/src/main/java/[package-name]
In the root of our project, we’ll create a new build.gradle file:
[project-name]/build.gradle:
[code language=”groovy”]
buildscript {
repositories {
maven { url “http://repo.spring.io/libs-snapshot” }
mavenLocal()
}
dependencies {
classpath(“org.springframework.boot:spring-boot-gradle-plugin:1.0.1.RELEASE”)
}
}
apply plugin: ‘java’
apply plugin: ‘eclipse’
apply plugin: ‘idea’
apply plugin: ‘spring-boot’
jar {
baseName = ‘getting-started’
version = ‘0.1.0’
}
repositories {
mavenCentral()
maven { url “http://repo.spring.io/libs-snapshot” }
}
dependencies {
compile(“org.springframework.boot:spring-boot-starter-web”)
testCompile(“junit:junit”)
}
task wrapper(type: Wrapper) {
gradleVersion = ‘1.11’
}
[/code]
Several items to mention here:
The ‘buildscript’ closure sets up the build itself. This is where the plugins used by the build are declared, along with the repositories in which they can be found.
Following that, there are several plugin applications.
- The java plugin provides the basic tasks related to a simple java project – compiling and packaging, among others.
- The eclipse and idea plugins allow project files to be created for eclipse and Intellij, respectively.
- The spring-boot plugin contains tasks that build executable jars and execute them using embedded tomcat using tasks
like ‘bootRun’, which we’ll use often in these tutorials.
Next the ‘repositories’ closure is used to declare where the project’s dependencies will be found.
After that, there is a ‘dependencies’ closure that contains the jars required by the project
Last, there is a standard gradle pattern – the task wrapper – which is used to enforce the version of gradle being used on the project, as well as allow easy execution of the build by users who do not have gradle installed. More information on that found here.
Application Configuration
In the source root of our project ([project-name]/src/main/java/[package-name]), create a file called ‘Application.java’. This file mirrors the one found in the first Spring-Boot tutorial, but since it serves as the foundation for upcoming tutorial sections, I’ll call out a few things already explained on the Spring.io site:
[project-name]/src/main/java/[package-name]/Application.java:
[code language=”java”]
package com.rodenbostel.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
[/code]
You’ll notice two major components of this file: the annotations, and the main method.
The annotations are marker interfaces used to alert the framework that this is a Spring config file (@Configuration), that you’d like to scan for beans to load in the current and child packages (@ComponentScan) and that you’d like to use auto configuration settings (@EnableAutoConfiguration). Auto configuration in Spring Boot takes the concept of convention over configuration to an almost Rails or Grails-like level. It provides basic configuration of an application – where to find properties files, how properties files are named when using Spring Profiles, configuration a DispatcherServlet (note the lack of web.xml), and much more. It is worth it to look further into what auto configuration is providing to insure your application does not conflict with it, especially if you’re planning on deploying to containers that also provide libraries on the class path by default (I’m looking at you, Websphere).
The main method simply allows the application to be executed from the command line. This includes the startup of your embedded container (in our case, Tomcat). It’s worth mentioning here that the return type of SpringApplication.run is an ApplicationContext object which can be further manipulated.
Creating a Controller
Again using the similar source to that of the Spring Boot demos on the Spring.io site, we’ll begin developing our app using a sample controller configuration as a RestController to verify our app is functioning correctly. In our source root ([project-name]/src/main/java/[package-name]), create a file called ‘SampleController.java’.
[project-name]/src/main/java/[package-name]/SampleController.java:
[code language=”java”]
package com.rodenbostel.sample;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@RequestMapping(“/”)
public String index() {
return “Greetings from Spring Boot!”;
}
}
[/code]
Here we are using constructs familiar since Spring MVC 3.5-ish. The RestController interface declares just that – a RESTful controller. This controller will return strings instead of views by default. The RequestMapping annotation on the only method in this class should be familiar, too. This calls for the controller to respond to requests at “/“ by executing the index() method. In this case, we’re responding with a simple String.
Execution
For this introduction, and the tutorials that follow, I’ll be using ‘gradle bootRun’ to execute the app. Upon executing ‘gradle bootRun’, in a browser, visit ‘http://localhost:8080/’, and admire you’re work. You should be looking at a simple string: ‘Greetings from Spring Boot!’.
Preparing for Part 2
Again, this post re-hashed most of what is found on the Spring.io site on the same topic. I hope this has included some additional insight that will help get you started. Since this will be the foundation for Parts 2 and beyond, the code up to this point can be found on Github. The next installment will start where this post left off. Check back soon for the next installment: Adding views using Thymeleaf.