Spring Boot Tutorial - 1. Configuration

The Spring framework is by far the most popular and easy to use solution for enterprise java applications. However, the enterprise world has improved quite a lot in the last few years, and Java apps are now as quick to build and launch in Spring as in any other new hip technology. If you missed it, Craig Walls wrote a nice little book on the subject.

This tutorial will focus on walking through the most important Spring Boot concepts and some other related technologies. It assumes that you already have some app development knowledge in either Java or in other languages. Also, please note that these articles are always opened for improvements, so feedback is much appreciated.

IDE

Any IDE can be used when developing Spring Apps, but we’ll use Eclipse since the Spring team created powerful tools to help with the development process. Find and install the Spring Tool Suite in the Eclipse Marketplace (under the Help tab).

Furthermore, you’ll have to make sure you are able to use the Gradle build system in your IDE. We’ll look in more detail at Gradle in just a few, but until then make sure to follow the steps:

  1. Download this file locally
  2. Click on Help -> Install New Software
  3. Click on Available Software sites
  4. Click the Import button
  5. Find the saved bookmarks.xml file and click OK.
  6. In the Work with text box paste the following: http://dist.springsource.com/milestone/TOOLS/gradle
  7. Press enter and wait for the options to load
  8. Select Tool Suite Gradle Integration
  9. Click Next
  10. Review the list of software that will be installed. Click Next again
  11. Review and accept licence agreement and Click Finish

Create a new app

We’ll use Spring Initializr to generate a starter project containing all the configuration and libraries needed for our application. However since we installed the Spring Tool Suite in Eclipse, we’ll use the IDE version of the Initializr:

  1. Go to File -> New -> Spring Starter Project
  2. We’ll use Gradle to manage project dependencies. Select Gradle(STS) from the Type dropdown
  3. Even though war is the popular packing solution for web applications, we’ll select jar from the Packing dropdown. Since Spring Boot comes packed with an internal Tomcat that will run the app for us, we don’t need to install an application server to run our app
  4. Change the group and package to io.veli
  5. Press Next>
  6. Search for the Web dependency and select it
  7. Search for the Thymeleaf dependency and select it
  8. Press Next>
  9. Press Finish>
  10. Wait for Eclipse do download and install the dependencies

You’ll have to wait a bit until everything is downloaded, but at some point you should end up with the following Spring starter project in your IDE:

I recommend using the Navigator tab to browse through your source files, since it follows the exact folder structure of your project. You can enable the Navigator view from Window -> Show View -> Navigator.

Run your app

For development purposes you can run your app directly in Eclipse. Later, we’ll also use the command line since this is the method you’ll follow to prepare your app for production deployment.

To run your app in Eclipse:

  1. Right click on the project name in the Navigator (left hand side). The name of your project should be demo if you followed along.
  2. Click on Run As and then on Spring Boot App

At this point, your app will either be compiled and started, or you’ll be greeted by this nice little warning: Errors exist in required project(s). If you’ll click on Proceed, you’ll end up with this error in the console: Error: Could not find or load main class io.veli.DemoApplication.

This error is most likely caused by some off configuration in the app classpath. The classpath is Java’s way of finding all the classes and packages in your project. Usually you don’t have to concern yourself with such dependencies since either the IDE or your build tool will handle all the internals. However, Eclipse may have a hard time figuring everything out from the start.

As you may recall, we chose Gradle as our dependency management system. This means that Gradle will download all the libraries needed in our project. To see what dependencies Gradle will manage, just open build.gradle (CTRL+SHIFT+R to easily search for files in your project):

The commands in this file help Gradle do all the build configuration heavy lifting for us. We are interested in the following lines:

dependencies {
	compile('org.springframework.boot:spring-boot-starter-thymeleaf')
	compile('org.springframework.boot:spring-boot-starter-web')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

Since we selected the Web and the Thymeleaf dependencies when we created our app, Gradle knows that the app relies on these libraries (also called jars), so they are downloaded and added to our app.

Let’s make sure the dependencies are indeed managed correctly:

  1. Right click on the project name in the Navigator (left hand side). The name of your project should be demo if you followed along.
  2. Go to Gradle and click Enable dependency management
  3. Right click on the project name again
  4. Go to Gradle and click Refresh Dependencies
  5. Try to run your app again

Now, your application should start properly and you’ll end up having the following message in your console:

Started DemoApplication in 2.972 seconds (JVM running for 3.424)

We are done with all the configuration and setup needed to have the app running - you can access it at http://localhost:8080/. From now on we can focus on writing code and building things.

Adding functionality

The model-view-controller pattern is a core concept in developing Spring apps. Browser requests are mapped by controllers which use the request data sent by the client to return an appropriate result.

To create a controller:

  1. Right click on the root package folder. If you followed along, the root package folder is src/main/java/io/veli
  2. Go to New and click on Folder
  3. Type in controller as the Folder name
  4. Right click on the newly created folder src/main/java/io/veli/controller
  5. Go to New and click Other
  6. Select Class from the options list, and click Next
  7. Type in TranslateController in the Name field
  8. Leave everything else as is, and click Finish

If everything went well, you’ll find the newly created java file in the controller folder. You can easily search for it by pressing CTRL + SHIFT + R, and type in the class name: TranslateController.java.

Let’s add some proper functionality. In our controller we’ll create a new method that will listen for requests containing English words, and return the translated word in the lovely German language:

First of all, we made sure that the TranslateController.java file is registered in Spring as a controller by annotating the class with @Controller. Since we also added the @RequestMapping(path="/translate") annotation, this controller will only listen to requests starting with the /translate keyword. An example of such a request is http://localhost:8080/translate/word/dog.json.

For demo purposes, we created a Map with English words as keys and their German meaning as values.

Our controller intercepts all requests starting with /translate, but it doesn’t do anything special for any specific set of requests. In order individualize such a set, we created a translateWord method that handles all requests paths matching the pattern /word/{word}.json: @RequestMapping(path="/word/{word}.json", method=GET).

Here are some URLs following this pattern:

  1. http://localhost:8080/translate/word/dog.json
  2. http://localhost:8080/translate/word/cat.json
  3. http://localhost:8080/translate/word/bunny.json

If you’ll rerun your app, clicking on these links should return the associated German word for you. Note that the requests start with the /translate keyword so that the right controller can take charge, and ends with a specific pattern defined in a method’s @RequestMapping annotation.

The translateWord method is extracting the {word} that needs to be translated directly from the request URL. This happens because we instructed the method to populate its String word parameter with a value extracted from the path: @PathVariable(value="word") String word.

Finally, note that the translateWord method returns a String annotated with @ResponseBody. This ensures that the method result will be returned in JSON format. This is why, for clarity, we added the .json extension in the method’s request mapping pattern. We’ll cover returning actual HTML pages built with Thymeleaf in later tutorials.

Configuration

If you are familiar with Java apps or with any other compiled language app for that matter, you’ll know that changes in your code will require recompilation and redeployment to take effect. It is quite common to avoid this process for various tasks by using configuration files. These externalize some of the app options, and allow you to update the app behavior directly.

If you followed along, Eclipse already created a default application.properties file under the resources folder. If the file is not there, simply create it:

  1. Right click on the resources folder New -> File
  2. In the dialog enter the file name application.properties
  3. Press Finish>

Make sure that you use the same file name, since based on this name convention Spring is able to find and load your properties.

For demo purposes, we’ll change the not found message received when searching for undefined words to something more friendlier. In the configuration file add the following line:

app.msg.not.found = Bummer! I don't know this word yet.

We can easily inject and use this property in our controller class:

In general, a Spring app handles messages through internationalization. We’ll cover it in later tutorials, but until then this simple example should do.

Next Steps

By know, you should be familiar with some of the concepts behind Spring Boot and the MVC architecture used to handle web requests and responses. A useful, more comprehensive read on this subject can be found here.

In the next tutorial we will add a database layer to our Translate App, and we’ll take a look at storing and retrieving data through the powerful Spring Data project.


Tutorial Contents

  1. Spring Boot Tutorial - Configuration
  2. Spring Boot Tutorial - SQL & Hibernate
  3. Spring Boot Tutorial - Thymeleaf
  4. Spring Boot Tutorial - REST APIs
  5. Spring Boot Tutorial - Security
  6. Spring Boot Tutorial - Elasticsearch
  7. Spring Boot Tutorial - MongoDB
  8. Spring Boot Tutorial - Testing
  9. Spring Boot Tutorial - Glossary