© Felipe Gutierrez 2016

Felipe Gutierrez, Pro Spring Boot, 10.1007/978-1-4842-1431-2_2

2. Your First Spring Boot Application

Felipe Gutierrez

(1)Albuquerque, New Mexico, USA

In this chapter you are going to install the Spring Boot CLI, learn more a little about it, and create your first Spring Boot application. You will learn how Spring Boot works internally so you have a better picture of this amazing technology.

You can create Spring Boot applications by using the Spring Boot Command Line Interface (CLI) or by using Maven, Gradle, and even Apache Ant. This chapter has step-by-step explanations on what needs to be done to set up your environment from the command line through using Spring Boot on an Integrated Development Environment (IDE). Let’s get started!

Installing Spring Boot CLI

Before you install the Spring Boot CLI, it’s necessary to check your Java installation, because you must have JDK 1.6 or higher in your computer. Sometimes it’s necessary to have the JAVA_HOME environment variable pointing to your Java installation and the java program in your PATH.

UNIX OSs: Linux, OS X, and Solaris

There are a lot of tools that can help you install the Spring Boot CLI. If you are using any UNIX environment, including Linux, OS X, or Solaris, you can use a very good tool named SDKMAN. You can find it at http://sdkman.io/ . Open a terminal window and execute the following:

$ curl -s get.sdkman.io | bash

After it finishes, you can execute the following line to run the sdk command:

$ source "$HOME/.sdkman/bin/sdkman-init.sh"

Then make sure that the sdk command is working by executing this line:

$ sdk version
SDKMAN 3.2.4

Next, it’s time to install the Spring Boot CLI, which you do by executing this command:

$ sdk install springboot

Once the CLI is installed, you can check if everything went okay by executing this request:

$ spring --version
Spring CLI v1.3.2.RELEASE

You should get the latest version of Spring Boot; in my case it’s release 1.3.2. Now you are ready to start using the Spring Boot CLI on a UNIX system.

Note

You can use the same sdk command to install Groovy and Gradle. You can install those two by executing: $ sdk install groovy and $ sdk install gradle.

There is another UNIX-like OS option called homebrew. This tool was initially developed for OS X users so they could install missing tools from the UNIX/Linux world. One of the benefits of brew is that it has a sandbox that doesn’t interfere with your system.

On OS X you can go to the http://brew.sh/ web site and read more about this particular tool. In order to install brew, you must execute this command:

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Once it finishes installing, follow the instructions to get it working from the command line. You might need to open a new terminal and/or do a source over the .bash_profile file to get it working, although if you have the latest version, you won’t need to do this. Just follow the instructions on the screen after you install brew. You can then execute the following command to install Spring Boot:

$ brew tap pivotal/tap
$ brew install springboot

If you are a Linux user, you can install brew (you can get more info at http://brew.sh/linuxbrew/ ) by executing this command:

$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

Then execute the same commands from above:

$ brew tap pivotal/tap
$ brew install springboot

That’s it; it’s very simple. One of the benefits of using the Linux version is that you don’t need sudo, because all the software is installed in your home directory.

Note

You can also use the brew command to install the software that we are going to use in the next chapters, including RabbitMQ, Redis, and MySQL.

Windows OS

If you are a Windows user or you don’t want to use the previous methods, you can download the ZIP binary distribution and uncompress it. These are the links of release 1.3.2:

These links are the binary versions, but if you wonder where those links are coming from, you can find them here: https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-installing-spring-boot.html#getting-started-manual-cli-installation . You must have the JAVA_HOME variable set (pointing to your Java SDK) and the SPRING_HOME variable pointing to where you uncompress the binary distribution. Also make sure to set up your PATH variable, which includes the %SPRING_HOME%in path (or, if you are using UNIX, it’s $SPRING_HOME/bin). By setting these variables to the environment, you will have access to the spring.bat or spring scripts.

Note

The binary distribution contains a Groovy version, so you are set if you want to run Groovy scripts. You can verify that your installation was successful by typing $ spring --version Spring CLI v1.3.2.RELEASE.

You have the Spring Boot CLI, so what’s next? In the previous chapter, you saw a simple web application written in Groovy and Java, and the way that you run it is by executing this command:

$ spring run *.groovy

or

$ spring run *.java

But there is more to it. Not only is the Spring Boot CLI useful for running the application but it also initializes and creates the structure you need. For example, you can create a base or minimal project by executing the following:

$ spring init  --build gradle myapp

This command will call the web service at https://start.spring.io (this is discussed in the following sections of this chapter) and will create a folder named myapp. The project is Gradle-based, although if you don’t include the --build gradle option, it will by default create a Maven-based project. Figure 2-1 shows the structure of the project.

A340891_1_En_2_Fig1_HTML.jpg
Figure 2-1. Spring Boot project structure

Figure 2-1 shows you the Spring Boot project structure created when you execute the spring init command. If you want to add more features—such as web, JPA, and Maven projects—you can execute the following command:

$ spring init -dweb,data-jpa,h2,thymeleaf --build maven myapp --force

This command will create a Spring Boot Maven project and will include all the necessary dependencies in the pom.xml file to run a Spring Boot web application. It will include libraries to handle web files (this will include the embedded Tomcat server), persistence (data-jpa), the H2 database engine (h2), and a viewer engine (thymeleaf). You need to use --force to override the previous myapp directory or you can change the name.

Don’t worry too much about what are those dependencies or how they create this project; you’ll learn more about this in the following sections.

Now you are set to start using the Spring Boot CLI with Groovy or Java and can create prototype applications. You can use the Spring Boot CLI to create “production-ready” apps, which will depend on how you set up your environment to use this tool. You’ll learn more about using the Spring Boot CLI in this chapter and later chapters.

Spring Boot with Maven and Gradle

If you already use Maven ( https://maven.apache.org/ ) or Gradle ( http://gradle.org/ ) as tools for compiling, testing, and building, you can use also Spring Boot. And as you might guess, you need to include some dependencies in order to use Spring Boot. The following sections explain what you need for every project in Spring Boot. You must see these as requirements if you want to use Maven or Gradle to develop Spring Boot apps.

Using Maven

Listing 2-1 shows the pom.xml file that you use every time you need to create a Spring Boot app.

Listing 2-1. pom.xml
<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <groupId>com.example</groupId>
    <artifactId>myapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>


    <!-- Spring Boot Parent Dependencies-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>


    <!-- Add dependencies: starter poms -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>


    <!-- Spring Boot Plugin for creating JAR/WAR files -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Listing 2-1 shows you the minimum pom.xml that you can have for any Spring Boot application. If you take a closer look, there is a <parent/> tag section where you need to include the spring-boot-starter-parent artifact. This particular dependency contains all you need to run your app. It contains all the descriptions of dependencies that a Spring Boot application needs, like all the dependencies of the Spring Framework (spring-core), Spring Test (spring-test), and more. You only need to use this parent pom.

Another section is the starter poms, where you declare the dependencies of the actual Spring Boot feature you want to use. Listing 2-1 shows the default starter, spring-boot-starter artifactId. The starter poms will bring all the dependencies that you need for your application, which is why you need to include just one starter pom. For example, if you are creating a web application, the only dependency you need is the spring-boot-starter-web artifact:

...    
<!-- Add dependencies: starter poms -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        ...
    </dependencies>
...

This dependency will include all the spring-core, spring-web, spring-webmvc, embedded Tomcat server, and other libraries related to the web application. A later section of this chapter explains more about the Spring Boot starter poms. At this point, you simply need to understand that you can include these dependencies in your main pom.xml file.

The last section is the Spring Boot Maven plugin, and it is included by declaring the spring-boot-maven-plugin artifact. This particular plugin will help you package your application as a JAR or WAR with the command: mvn package. It also has several goals/tasks that you can use, like the one in the previous chapter for running the Spring Boot app: mvn spring-boot:run. You can get more information about this plugin at its web site: http://docs.spring.io/spring-boot/docs/1.3.1.RELEASE/maven-plugin/ .

You are set now with Maven. You are going to create your first Spring Boot app later, though. Right now I want you to know all the possible ways to use Spring Boot.

Using Gradle

You can use Gradle ( http://gradle.org/ ) to compile, test, and build Spring Boot apps. Just as with Maven, you need to have a minimum description for creating Spring Boot applications. See Listing 2-2.

Listing 2-2. build.gradle
buildscript {
    repositories {
        jcenter()
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.1.RELEASE")
    }
}


apply plugin: 'java'
apply plugin: 'spring-boot'


jar {
    baseName = 'myproject'
    version =  '0.0.1-SNAPSHOT'
}


repositories {
    jcenter()
    maven { url "http://repo.spring.io/snapshot" }
    maven { url "http://repo.spring.io/milestone" }
}


dependencies {
    // starter poms dependencies
    compile('org.springframework.boot:spring-boot-starter')
}

Listing 2-2 shows you the minimum build.gradle file that you need to use to run Spring Boot applications. The first section you need to look at is the buildscript, where you add the dependency of the Spring Boot Gradle plugin. This plugin contains the parent pom (which contains all the base dependencies) and the tasks that will help you compile, run, and package your Spring Boot apps. It declares a repositories section where the Gradle tool will look for Maven-like servers that provide all the libraries needed by the dependencies section that is declared.

Next is the section where you apply the plugins, in this case the apply plugin: spring-boot. This will add the tasks mentioned above. Then, either you are creating a jar or a war declaration that contains the baseName and the version. Next is the repositories section, where all the dependencies can be found to be downloaded into your environment. Finally there is the dependencies section, where you put all the starter poms in the form of org.springframework.boot:spring-boot-starter-<feature/technology>. Listing 2-2  shows the default spring-boot-starter artifact.

So, for example if you want to create a web application with testing, you need to add the following in the dependencies section:

compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")

If you want to use a starter pom, you have to add the following syntax.

For Maven:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-[TECHNOLOGY]</artifactId>
</dependency>

For Gradle:

compile("org.springframework.boot:spring-boot-starter-[TECHNOLOGY]")

As you can see, the Spring Boot team created a very easy-to-follow naming convention for all the starter poms. Note also that you don’t need to add any dependency version, because the starter poms will take care of that.

Now you are set to use Gradle for your Spring Boot apps.

Note

When using Gradle you can use the Gradle wrapper, which allows you to have a binary Gradle when you want to distribute your application and the computer doesn’t have Gradle. See http://www.gradle.org/docs/current/userguide/gradle_wrapper.html .

Spring Boot Using External Tools

You have learned how to install Spring Boot CLI to use Groovy or Java for your apps, and you have seen the minimal declaration dependencies for using Maven or Gradle. You do need to create a directory structure as well. If you want to add more features, you also need the names of the starter poms. (I showed you only the minimum requirements for Maven and Gradle, right?)

Well, there is a tool that you can use without using an IDE. The Spring team created a reference architecture tool/service called Spring Initializr, and you can use it to create a complete project with all the dependencies that you need.

Spring Boot Using the Spring Initializr

You can find this reference architecture service at http://start.spring.io . It’s hosted by Pivotal Web Services. Right now it’s on its second iteration. It provides a simple version (Figure 2-2) and a full version (Figure 2-3) and both look great!

A340891_1_En_2_Fig2_HTML.jpg
Figure 2-2. Simple view of the Spring Initializr ( http://start.spring.io )
A340891_1_En_2_Fig3_HTML.jpg
Figure 2-3. Full version of the Spring Initializr

Figure 2-2 shows an interface where you can create your Spring Boot application. You can include all the dependencies by just typing web, security, or jpa. If you click the Generate Project button, you will get a ZIP file that contains the structure and the pom.xml or build.gradle file, depending on what project type you choose. You can also select the Spring Boot version and the programming language to use (Groovy or Java).

Figure 2-3 shows you the full version of the Spring Initializr, and if you keep scrolling down, you will find all the dependencies that you can add by clicking on the checkboxes. After you select the features you want to use, click the Generate Project button to get the ZIP file that contains your project.

Using the Spring Initializr with UNIX cURL

The Spring Initializr can be accessed using the UNIX cURLcommand because at the end it is a web service and it exposes a RESTful API. So, for example, if you wanted to create a simple project that contains just the minimum files, you could execute the following command:

$ curl -s https://start.spring.io/starter.zip -o myapp.zip

This command will create a myapp.zip file that contains all the structure for the Spring Boot app. And by default it contains a Maven project with its pom.xml file and a Maven wrapper. This means that you aren’t required to have Maven installed, because it comes with it. You can easily use all the goals/tasks to compile, build, and run your Spring Boot apps.

If you want the minimum structure for a Gradle-based project, just execute the following command:

$ curl -s https://start.spring.io/starter.zip -o myapp.zip –d type=gradle-project

With this command you will have a build.gradle and a Gradle wrapper. They will help you to compile, build, and run your Spring Boot apps without having to install Gradle.

If you want to create a Spring Boot application with a web feature, you can execute the following command:

$ curl -s https://start.spring.io/starter.zip -o myapp.zip -d type=maven-project -d dependencies=web

Using this command, you will have in your pom.xml file the spring-boot-starter-web artifact as a dependency. Sometimes you will want to see how the pom.xml or build.gradle file looks when you’re adding some dependencies. You can generate these files by executing the following command if you want only the Maven pom.xml:

$ curl -s https://start.spring.io/pom.xml -d packaging=war -o pom.xml -d dependencies=web,data-jpa

This command will generate only the pom.xml with a WAR package type and the spring-boot-starter-web and the spring-boot-starter-data-jpa artifacts. If you want the build.gradle file as well, you execute the following command:

$ curl -s https://start.spring.io/build.gradle -o build.gradle -d dependencies=web,data-jpa

This command will generate only the build.gradle as a JAR (this is the default option, unless you use the -d packaging flag) and it will contain the same starters from the previous command. So, as you can see, you have several options for creating a Spring Boot application.

Note

You can get more details about what other options you can set when executing the cURL command. Just execute this command: $ curl start.spring.io.

Notice that the -s option is used in these examples. It allows you to force the cURL command to be silent, and you can remove it and see the progress of the ZIP file being downloaded. You can get more information about all the flags shown in the cURL examples by Googling them or executing the $man curl command.

Spring Boot Using Spring Tool Suite (STS)

If you are already using the Eclipse IDE , you can install the STS as a plugin or download it at https://spring.io/tools/sts/all . The STS is available for all the different operating systems. See Figure 2-4.

A340891_1_En_2_Fig4_HTML.jpg
Figure 2-4. Spring Tool Suite (STS) web page ( https://spring.io/tools/sts/all )

One of the benefits of using the STS is that it comes with Spring Boot support. Choose File ➤ New to see the Spring Starter Project option (it’s the first option shown in Figure 2-5).

A340891_1_En_2_Fig5_HTML.jpg
Figure 2-5. Choose File ➤ New ➤ Spring Starter Project

If you click on the Spring Starter Project option, the Spring Starter Project wizard will appear. This is where you put all the general information about your Spring Boot project. See Figure 2-6.

A340891_1_En_2_Fig6_HTML.jpg
Figure 2-6. The Spring Starter Project wizard—general information about the Spring Boot project

Figure 2-6 shows you the first page of the wizard where normally you select the project type (Maven or Gradle), the Java version, the language (Java or Groovy), and some other Maven descriptors. If you click Next, the dependencies page appears. See Figure 2-7.

A340891_1_En_2_Fig7_HTML.jpg
Figure 2-7. Spring Starter Project wizard—dependencies selection

Figure 2-7 shows you the next page of the wizard, where you select the dependencies for your application and the version of Spring Boot to use. You can choose the latest snapshot. And if you click Next, you can see the summary of your Spring Boot project. See Figure 2-8.

A340891_1_En_2_Fig8_HTML.jpg
Figure 2-8. Spring Starter Project wizard—summary page

Figure 2-8 shows you the final step and summary of what the wizard will generate, because it gives access to the URL and all the parameters that you can use with the cURL command. You could even paste the whole URL in a browser and get the ZIP file.

The Spring Starter Project wizard will download and uncompress in the background and set the workspace with the Spring Boot project you created. As you can see, you have another option to create Spring Boot applications. One of the major benefits of using the STS is that it has support for Spring Boot. This means wizard support and code-completion support for the application.properties and the application.yml files, as well as cloud support and some other features.

Your First Spring Boot Application

It’s time to create your first Spring Boot application. The idea of this application is simple—it’s a journal application. You will start with something simple in this chapter, just enough to get to know the Spring Boot internals. During the rest of the book, you will modify it so at the end you have a complete and production-ready Spring Boot application.

Spring Boot Journal

This application is called “ Spring Boot Journal” and it’s a simple application in which you will have a collection of entries that shows the main ideas over a timeline.

You have installed Spring Boot CLI and you already know more about the different options for using Spring Boot with Maven or Gradle. You also know that you can use an IDE like the STS and use the Spring Boot project wizard. Regardless of the method you choose, it will be the same for this application. It’s most important to describe the main concepts behind the Spring Boot technology.

These steps show you how to create the Spring Boot journal application using the STS:

1.

Open the STS and select File ➤ New ➤ Spring Starter Project. You can add any package name or any group or artifactId if you want, just make sure to select Java as the language. I will use both pom.xml and build.gradle files, so you have all the dependencies this app needs. See Figure 2-9. After entering all the necessary information, click Next to move to the dependencies page.

A340891_1_En_2_Fig9_HTML.jpg
Figure 2-9. Spring Starter project—Spring Boot journal

Figure 2-9 shows you the first page of the Spring Starter Project wizard. As I said before, you can put whatever information you like. The important part are the classes you are going to use, but if you want to follow along, this is the information I used in the example:

Field

Value

Name

spring-boot-journal

Type

Maven

Packaging

Jar

Java Version

1.8

Language

Java

Group

com.apress.spring

Artifact

spring-boot-journal

Version

0.0.1-SNAPSHOT

Description

Demo project for Spring Boot

Package

com.apress.spring

2.

On the next page of the Spring Starter Project wizard, you choose the technologies that Spring Boot Journal will use. In this case, check Web (Web), Template Engines (Thymeleaf, which is a template engine capable of processing and generating HTML, XML, JavaScript, CSS, and text that is suitable for the view layer of web applications, a better approach to the Java Server Pages or JSPs, because it’s faster and more reliable), Data (JPA), and Database (H2). This example uses the JPA technology with the in-memory H2 database.

See Figure 2-10. After choosing your dependencies, you can click Finish.

A340891_1_En_2_Fig10_HTML.jpg
Figure 2-10. Spring Starter Project wizard —dependencies —Spring Boot journal
3.

Take a look at the project’s file structure. You should have something similar to Figure 2-11.

A340891_1_En_2_Fig11_HTML.jpg
Figure 2-11. Spring Boot journal project structure
4.

Next, take a look at the pom.xml file that was generated. You should have something like Listing 2-3.

Listing 2-3. pom.xml
<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <groupId>com.apress.spring</groupId>
    <artifactId>spring-boot-journal</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>


    <name>spring-boot-journal</name>
    <description>Demo project for Spring Boot</description>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Listing 2-3 shows you the pom.xmlof the Spring Boot journal. The important part in this pom is the dependencies section, which contains all the starter poms that you selected in the wizard. Remember, you are going to use a web technology (your Spring Boot journal is a web application—spring-boot-starter-web), a template engine (Thymeleaf—spring-boot-starter-thymeleaf) that will render the HTML pages of the journal app, a Data (JPA – spring-boot-starter-data-jpa) technology that will take care of the data persistence, a Database engine (H2), an in-memory database, and a test unit framework (spring-boot-starter-test) that will help with all the unit and integration testing. For now, and for your first application, the H2 database engine will be enough. Later in the book you will switch to different database engines, such as MySQL, MongoDB, or Redis.

If you selected a Gradle project, Listing 2-4 shows you the build.gradle file.

Listing 2-4. build.gradle
buildscript {
    ext {
        springBootVersion = '1.3.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}


apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'


jar {
    baseName = 'spring-boot-journal'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8


repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('com.h2database:h2')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}


eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}


task wrapper(type: Wrapper) {
    gradleVersion = '2.9'
}

Listing 2-4 shows the build.gradle file. The important part is to take a look at the dependencies sections where all the starter poms are declared. It’s very similar to Maven. I only want to comment about the last section, where there is a Eclipse declaration. This will help you to get the correct runtime environment when you import this project to STS or any other Eclipse IDE version.

5.

For this journal, you need to create a domain class. See Listing 2-5, which shows the Journal class.

Listing 2-5. com.apress.spring.domain.Journal.java
package com.apress.spring.domain;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;


@Entity
public class Journal {


        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;
        private String title;
        private Date created;
        private String summary;


        @Transient
        private SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");


        public Journal(String title, String summary, String date) throws ParseException{
                this.title = title;
                this.summary = summary;
                this.created = format.parse(date);
        }


        Journal(){}

        public Long getId() {
                return id;
        }


        public void setId(Long id) {
                this.id = id;
        }


        public String getTitle() {
                return title;
        }


        public void setTitle(String title) {
                this.title = title;
        }


        public Date getCreated() {
                return created;
        }


        public void setCreated(Date created) {
                this.created = created;
        }


        public String getSummary() {
                return summary;
        }


        public void setSummary(String summary) {
                this.summary = summary;
        }


        public String getCreatedAsShort(){
                return format.format(created);
        }


        public String toString(){
                StringBuilder value = new StringBuilder("JournalEntry(");
                value.append("Id: ");
                value.append(id);
                value.append(",Title: ");
                value.append(title);
                value.append(",Summary: ");
                value.append(summary);
                value.append(",Created: ");
                value.append(getCreatedAsShort());
                value.append(")");
                return value.toString();
        }
}

Listing 2-5 shows you the Journal domain class. Because you are using the JPA technology, you need to use the @Entity, @Id, and @GeneratedValue annotations so this class gets marked as JPA entity and can be persisted to the database. You are going to see more of these classes in later chapters of the book. As you can see, there is also a @Transient annotation, which will indicate to the JPA engine not to persist that property, because it’s only being used to format the date. This class has two constructors, one with no arguments and is needed for the JPA engine and the other with some arguments that you are going to use to populate the database.

There is an override of the toString method, which will be useful for printing the records.

6.

Next, you need to create a persistence mechanism for the journal data. You are going to use the Spring Data JPA technology by creating an interface and extending it from the JpaRepository interface. See Listing 2-6.

Listing 2-6. com.apress.spring.repository.JournalRepository.java
package com.apress.spring.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.apress.spring.domain.Journal;


public interface JournalRepository extends JpaRepository<Journal, Long> {  }

Listing 2-6 shows you the Spring Data Repository JPA technology, and it’s easy to extend the JpaRepository interface. The JpaRepository is a marker interface that allows the Spring Data Repository engine to recognize it and apply the necessary proxy classes to implement not only the base CRUD (Create, Read, Update, Delete) actions, but also some custom methods. You can do this by having some naming conventions, such as findByTitleLike or findBySummary or even findByTitleAndSummaryIgnoringCase. All the actions will then be set as transactional by default. The JpaRepository also has some convenient behavior because you can add sortable and paging actions to your data.

Don’t worry too much about this right now, because you’ll learn more about the Spring Data (JDBC and JPA) in its own chapter. For now, the only thing you need to do is create the interface and extend from the JpaRepository marker interface.

7.

Because this is a web application, you need to create a web controller. See Listing 2-7.

Listing 2-7. com.apress.spring.web.JournalController.java
package com.apress.spring.web;

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


import com.apress.spring.repository.JournalRepository;

@Controller
public class JournalController {


        @Autowired
        JournalRepository repo;


        @RequestMapping("/")
        public String index(Model model){
                model.addAttribute("journal", repo.findAll());
                return "index";
        }
}

Listing 2-7 shows the web controller, which will send back all the journal entries. In this case the class is marked with the @Controller, which is a marker for the Spring MVC engine so this class is treated as web controller. The @Autowired annotation will instantiate the JournalRepository variable repo, so it can be used in the index method.

The index method is marked with the @RequestMapping annotation, which will make this method the handler for every request in the default route /. If you take a look, there is a Model class parameter that will be created, and it will add an attribute named journal with a value that is the result of calling the JournalRepository interface, repo.findAll() method. Remember that by extending a JpaRepository, you have by default different methods, and one of them is the findAll method. This method will return all the entries from the database. The return will be the name of the page index, then the Spring MVC engine will look for the index.html in the templates folder.

8.

Then in the src/main/resources/templates folder, you need to create the index.html file. See Listing 2-8.

Listing 2-8. src/main/resources/templates/index.html
<!doctype html>
<html lang="en-US" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8"></meta>
  <meta http-equiv="Content-Type" content="text/html"></meta>
  <title>Spring Boot Journal</title>
  <link rel="stylesheet" type="text/css" media="all" href="css/bootstrap.min.css"></link>
  <link rel="stylesheet" type="text/css" media="all" href="css/bootstrap-glyphicons.css"></link>
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css"></link>
</head>


<body>
<div class="container">
  <h1>Spring Boot Journal</h1>


  <ul class="timeline">
   <div th:each="entry,status : ${journal}">
    <li th:attr="class=${status.odd}?'timeline-inverted':''">
      <div class="tl-circ"></div>
      <div class="timeline-panel">
        <div class="tl-heading">
          <h4><span th:text="${entry.title}">TITLE</span></h4>
          <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> <span th:text="${entry.createdAsShort}">CREATED</span></small></p>
        </div>
        <div class="tl-body">
          <p><span th:text="${entry.summary}">SUMMARY</span></p>
        </div>
      </div>
    </li>
   </div>
  </ul>
</div>
</body>
</html>

Listing 2-8 shows you the index.html file that will be rendered using the Thymeleaf engine, which is why you have an XML namespace in the html tag. What is important here is the th:each instruction. It will get the journal entries as a collection (by using the entry variable and the status variable in the index of each iteration) and it will iterate to create different tags based on the number of entries. To access the property for each entry, you use the th:text instruction.

9.

As you can see in Listing 2-8, there are some CSS defined. The important one is style.css. (I borrowed this style from Jake Rocheleau at http://blog.templatemonster.com/2014/04/23/tutorial-build-vertical-timeline-archives-page-using-bootstrap/ .) I modified and added this style.css file to the book’s source companion code. You can download it from the Apress web site. It’s important to know that Spring Boot will look for the static/ path to collect all the public files that you want to expose to the web, this will be the case with JavaScript, image files, and CSS files.

10.

Now the important part, the main application. See Listing 2-9

Listing 2-9. com.apress.spring.SpringBootJournalApplication.java
package com.apress.spring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class SpringBootJournalApplication {


    public static void main(String[] args) {
        SpringApplication.run(SpringBootJournalApplication.class, args);
    }
}

Listing 2-9 shows you the main application. You don’t need to do anything, and this is the class that was generated when you use the Spring Starter Project wizard. You are ready to run it, but wait! Where is the data? You need to inject some data so you can see the result. Modify the SpringBootJournalApplication class to look like Listing 2-10.

Listing 2-10. com.apress.spring.SpringBootJournalApplication.java
package com.apress.spring;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;


import com.apress.spring.domain.Journal;
import com.apress.spring.repository.JournalRepository;


@SpringBootApplication
public class SpringBootJournalApplication {


    @Bean
    InitializingBean saveData(JournalRepository repo){
        return () -> {
            repo.save(new Journal("Get to know Spring Boot","Today I will learn Spring Boot","01/01/2016"));
            repo.save(new Journal("Simple Spring Boot Project","I will do my first Spring Boot Project","01/02/2016"));
            repo.save(new Journal("Spring Boot Reading","Read more about Spring Boot","02/01/2016"));
            repo.save(new Journal("Spring Boot in the Cloud","Spring Boot using Cloud Foundry","03/01/2016"));
        };
    }


    public static void main(String[] args) {
        SpringApplication.run(SpringBootJournalApplication.class, args);
    }
}

Listing 2-10 shows the final version of the journal app. One thing to mention is the saveData method that is returning an InitializingBean. This particular class is always called when the Spring engine is creating the instance to initialize it. In this case, the method will be executed before the application finishes running.

In order to run it, select the SpringBootJournalApplication.java class from the Package Explorer view and right-click on it. Then choose Run As ➤ Spring Boot App. Once it's running you can open a browser and point to http://localhost:8080. You should see something like Figure 2-12.

A340891_1_En_2_Fig12_HTML.jpg
Figure 2-12. TheSpring Boot journal web application

Figure 2-12 shows you the result of running the Spring Boot journal application. If you analyze it in more detail, probably what is most time consuming will be the graphic design rather than the code. With only a few lines of code, you have a very cool Spring Boot app. You will modify this app in the remaining chapters.

You can stop your application by pressing Ctrl+C in the terminal where the application is running.

What happens if you want to expose this journal as a service? It would be nice to have a request to the http://localhost:8080/journal and the response be JSON data. You need to modify the JournalController class. You are going to add a new method that will handle the /journal route and respond as JSON data.

Go to your JournalController class and modify it to look like Listing 2-11.

Listing 2-11. com.apress.spring.web.JournalController.java
package com.apress.spring.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.apress.spring.domain.Journal;
import com.apress.spring.repository.JournalRepository;


@Controller
public class JournalController {


    @Autowired
    JournalRepository repo;


    @RequestMapping(value="/journal", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public @ResponseBody List<Journal> getJournal(){
        return repo.findAll();
    }


    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("journal", repo.findAll());
        return "index";
    }
}

Listing 2-12 shows you the modified version of the JournalController class. Remember that at some point this will become a service, so by adding the getJournal method and using the @ResponseBody, it will automatically respond with JSON data. But how does Spring Boot know about transforming the objects into the JSON format? Well, this is not Spring Boot, it’s the Spring MVC module. When you use the @ResponseBody annotation, Spring MVC will automatically use the correct HTTP message converters to transform your response into JSON data.

If you run the application again and point your browser to http://localhost:8080/journal, you should get something similar to Figure 2-13.

A340891_1_En_2_Fig13_HTML.jpg
Figure 2-13. Added a JSON response at http://localhost:8080/journal

Now you can create better applications that actually use this data to be exposed as a nice web interface. My intention for the journal web interface was just as an example, and I bet you can create a better looking web interface.

How Spring Boot Works

I think now is time to see how Spring Boot does it; how it works internally to relieve the developer from the headache of a J2EE web application. If you are a Spring or J2EE developer, you saw that you didn’t use a configuration file—no XML (web.xml), no @Configuration class, or any other Spring Beans definition file.

Maybe you are thinking that Spring Boot generated code—some classes to create all the necessary files to run this application—but that’s not the case, Spring Boot never generates code and will never output any source code. Remember that I said that Spring Boot is an opinionated technology, which means that it follows the best practices to create a very robust application with minimum effort.

Let’s see what is really happening when you run the SpringBootJournalApplication app. Listing 2-10 shows the main application. It is marked with the @SpringBootApplication annotation. This annotation looks like Listing 2-12.

Listing 2-12. org.springframework.boot.autoconfigure.SpringBootApplication.java
package org.springframework.boot.autoconfigure;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {


    Class<?>[] exclude() default {};

    String[] excludeName() default {};

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};


    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};


}

Listing 2-12 shows the @SpringBootApplication annotation. What is important to see is that this is a composed annotation because it contains the @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations. Don’t worry I will explain all these annotation in the following chapters. In version 1.0 of Spring Boot, you needed to use these three annotations to create a Spring Boot app. Since version 1.2.0, the Spring team created this enhanced @SpringBootApplication annotation. Remember, Spring Boot tries to simplify everything without having a configuration file.

The important key for Spring Boot to work is the @EnableAutoConfiguration annotation, because it contains the Auto-Configuration feature, and this is where it all starts to happen. Spring Boot will use auto-configuration based on your classpath, your annotations, and your configuration to add the right technology and create a suitable application. This means that all those annotations facilitate how Spring Boot will configure your app.

To sum up, in Listing 2-10 Spring Boot uses the @SpringBootApplication and the auto-configuration (based on the @EnableAutoConfiguration annotation) to try to identify all your components. First it will inspect your classpath, and because your dependency is a spring-boot-starter-web, it will try to configure the application as a web application. It will also identify that the JournalController class is a web controller because it is marked with the @Controller and because it contains the @RequestMapping annotations. And because the spring-boot-starter-web has the Tomcat server as a dependency, the Spring Boot will use it when you run your application.

Yes, a Tomcat server. Spring Boot has all these non-functional features that bring more to your application. You will learn more about this in later chapters, but for now you need to know that every time you create a web application, you will have a Tomcat server embedded. Note that you can exclude Tomcat and use another server like Jetty or Undertow.

You can also create a standalone application, by going to the command line and executing this:

$ mvn package

This command will create a JAR file in the target folder. Then you can execute the following command:

$ java -jar target/spring-boot-journal-0.0.1-SNAPSHOT.jar

You will have a running application (go to the http://localhost:8080). This technique helps to create and distribute the application to your clients.

Summary

This chapter showed you how to install and use Spring Boot with your first Spring Boot Journal application. You saw that there are many possibilities for using Spring Boot—by command line with the Spring Boot CLI; using the Spring Initializr web service with cURL; and by using the Spring Tool Suite (STS).

With your first application, you saw how easy it was to integrate different technologies and, with a few lines of code, have a good looking and functional web application. You also learned how Spring Boot works internally and how it creates your application based on your classpath and annotations.

The next chapter goes deeper into a configuration that you can use to extend Spring Boot even more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175