Building Applications with Spring 5 and Kotlin

5 (1 reviews total)
By Miloš Vasić
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Starting Up

About this book

Kotlin is being used widely by developers because of its light weight, built-in null safety, and functional and reactive programming aspects. Kotlin shares the same pragmatic, innovative and opinionated mindset as Spring, so they work well together. Spring when combined with Kotlin helps you to reach a new level of productivity. This combination has helped developers to create Functional Applications using both the tools together. This book will teach you how to take advantage of these developments and build robust, scalable and reactive applications with ease.

In this book, you will begin with an introduction to Spring and its setup with Kotlin. You will then dive into assessing the design considerations of your application. Then you will learn to use Spring (with Spring Boot) along with Kotlin to build a robust backend in a microservice architecture with a REST based collaboration, and leverage Project Reactor in your application. You’ll then learn how to integrate Spring Data and Spring Cloud to manage configurations for database interaction and cloud deployment. You’ll also learn to use Spring Security to beef up security of your application before testing it with the JUnit framework and then deploying it on a cloud platform like AWS.

Publication date:
May 2018
Publisher
Packt
Pages
310
ISBN
9781788394802

 

Starting Up

Welcome! You are starting a long trip into the unknown: the unknown kingdom of Spring Framework. Luckily, you have the right guide and great companions! You have us! In this book, you will discover what Spring Framework is and how powerful it can be in modern web application development. We will teach you all about workflow with the framework and guide you through a real-world application example. Get ready to learn!

This chapter will cover the following points:

  • Defining your mission
  • Separating code into independent entities
  • Planning your environment
  • Preparing the working environment
  • Setting up a Git repository
 

What is your mission?

Your mission, as we mentioned, will be making a real-world application. What can be a better learning path than building real things from scratch through to production deployment? Our real-world application example will have a real theme!

We will create a REST application that will represent the application programming interface (API) for other applications. The theme for our application will be simple: management for user Notes and TODOs.

Imagine that there is a real-world mobile application that manages all these Notes and TODOs. That application will need a REST API so that all the data is synchronized to the backend. The story is simple. The user creates a Note or TODO. The user's mobile application then, at some point, does the synchronization. After some time, the user updates the content in it. Again, data is synchronized with the remote backend instance. Then, after a year, the user buys a new device that has a plain mobile application running. Luckily, the mobile application will synchronize with the remote backend instance again and get all the Notes and TODOs the user created.

So, what will this REST API do?

It will expose to the end user API calls for all Create, Read, Update, and Delete (CRUD) operations. The data we create or modify will be stored in the persistence layer. In our case, that will be MySQL database. Using Spring Security, we will create user roles so certain user profiles can do various things, such as creating the other users or modifying the main application content. To make things more interesting, we will create microservices responsible for various tasks.

Before we deploy, we will first test our code with the proper tests. We will also write unit tests. All tests will cover some of the core functionality so that our application is sufficiently stable to be deployed. We will deploy to Apache Tomcat and to Amazon AWS Elastic Beanstalk.

 

Separating code into independent entities

Before we start with the implementation, we will separate our code into independent entities. Each entity will cover a single responsibility and therefore will be implemented when we cover a certain Spring functionality.

We will start with the main classes that will represent the data we will actually handle: Notes and TODOs. Then we will describe user-related stuff: the users themselves and the roles we plan to assign to them. Later, when we actually implement most of them, we will introduce some new entities to cover additional responsibilities. This will be explained in Chapter 3, Building Your First Spring RESTful Service with Kotlin.

Describing entities

The main entities that we will use and that will hold the data are Notes and TODOs. We can consider each of them as an entry that will be stored and that has common attributes:

  • ID: Universally Unique IDentifier (UUID) String
  • Title: String
  • Message: String
  • Location: String value that represents serialized Location class into JSON.

Here are all the entities that we use:

  • Note: The Note entity will represent Notes in the system with all common attributes.
  • TODO: The TODO entity will represent TODOs in the system with all common attributes and timestamps for a scheduled time.
  • User: The User entity will be completely independent of the main data entities. The user will represent the user and all the attributes that the user of the system can have, including assigned roles. The user will have the following attributes:
    • ID: UUID String
    • Email: String
    • Password: String
    • First name: String
    • Last name: String
    • Roles: String
  • Enabled: Boolean representing whether the user has activated the account or whether it has been activated by the user from a higher user hierarchy
  • Created on: Long representing UTC timestamp when the user was created
  • Updated on: Long representing UTC timestamp when the user was updated

In later stages, we can introduce additional attributes if there is a need. For now, we will stick to the most important ones we just described.

 

Planning your development

For every project you do, for big and complex projects, and for small ones too, planning is crucial! We will plan our development according to the chapter structure of this book. So, some stuff will be done first and some later. As you have probably realized, user-related functionalities will be provided when we touch on Spring Security. Until then, we will be focused on the main data entities and their relationship with Spring Framework and API clients as well.

Before you get into the deep implementation, it would be wise to plan your work first. As we already did, you should identify all your entities and the relations between them. You must be aware of potential hard connections between them. The best scenario is that each entity is completely independent and not aware of others. In our case, the user entity does not have any awareness of our main data entities, Notes, and TODOs, and vice versa.

Then, if we put all this on paper, we can consider what environments we will have. A common practice is that we have development, staging, and production environments. For bigger projects, sometimes a preproduction environment is also used. In our case, we will have a local development environment, too. The local development environment will be the one we will use for all these exercises. We will use our local working machines running an instance of MySQL and our Spring Framework application.

You must plan how will you deploy the application. For example, an application can run on Apache Tomcat or Amazon AWS. These are not the only options available. Depending on your needs, you will choose a proper deployment platform and deployment scenario. We will discuss this in more detail in Chapter 10, Project Deployment.

 

Preparing the working environment

Finally, it's time to prepare our working environment. We will prepare all the software needed to develop and run our application. For this process, we will need the following:

  • Git
  • JDK
  • IDE
  • Spring 5
  • Postman

For a proper development machine, you can use any computer having, for example, an i5 processor (or more powerful) with at least 8 GB of RAM. These are the main characteristics. You can do your development on Microsoft Windows, Linux, or macOS. All the development mentioned in this book was done on macOS Sierra (version 10.12.6).

Installing Git

We will use Git as our version control system. To install it, follow the procedure for your OS. We will provide guidance for the following:

  • Microsoft Windows
  • Linux (Debian, Ubuntu, Fedora, and raw source code)
  • macOS

Microsoft Windows

Here are the steps for installing Git on Microsoft Windows:

  1. Download Git for Microsoft Windows from the following location: https://git-for-windows.github.io/.
  2. Start the installer and follow the instructions.
  3. Open the Command Prompt.
  4. Configure Git with the following commands:
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"

macOS

To install Git on macOS, we recommend that you install Xcode with command-line tools from the App Store. Then, open Terminal and verify the Git version:

$ git -version 
git version 2.7.0 (Apple Git-66)  

Linux

Follow the installation steps for your distribution.

Debian and Ubuntu

The following are the steps to install Git on Debian and Ubuntu:

  1. Open Terminal.
  2. Use the following commands to start the installation:
$ sudo apt-get update 
$ sudo apt-get install git
  1. Verify the installation:
$ git -version
  • The output should be something like the following:
git version 2.9.2 
  1. Configure Git with the following commands:
$ git config --global user.name "Your Name" 
$ git config --global user.email "[email protected]"

Fedora

The following are the steps to install Git on Fedora:

  1. Open Terminal.
  2. Depending on your Fedora version, use YUM or DNF to install Git as follows:
$ sudo dnf install git 
//or
$ sudo yum install git
  1. Verify the installation:
$ git -version
  • The output should be something like the following:
git version 2.9.2
  1. Configure Git with the following commands:
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"

Building Git from the source code

If you prefer to build your stuff from source code, you can do the same with Git.

Debian and Ubuntu

To build from source, you need some dependencies installed:

  1. Open Terminal and install the following dependencies:
$ sudo apt-get update
$ sudo apt-get install libcurl4-gnutls-dev libexpat1-dev gettext libz-dev libssl-dev asciidoc xmlto docbook2x
  1. Navigate to your preferred directory.
  2. Clone the Git source code as follows:
$ git clone https://git.kernel.org/pub/scm/git/git.git
  1. Build Git as follows:
$ make all doc info prefix=/usr
$ sudo make install install-doc install-html install-info install-man prefix=/usr
We installed Git in the /usr directory. Use a different filesystem location if you prefer.

Fedora

The following are the steps to build from the source code:

  1. As was the case with Debian and Ubuntu, install the dependencies needed to build Git as follows:
$ sudo dnf install curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto docbook2X
  • If you have an older version of Fedora, run the following commands:
$ sudo yum install epel-release
$ sudo yum install curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto docbook2X
  1. Symlink docbook2X to the filename that the Git build expects:
$ sudo ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
  1. Navigate to your preferred directory.
  2. Clone the Git source code as follows:
$git clone https://git.kernel.org/pub/scm/git/git.git
  1. Finally, build Git:
$ make all doc prefix=/usr
$ sudo make install install-doc install-html install-man prefix=/usr
We installed Git in the /usr directory. Use a different filesystem location if you prefer.

Congratulations! You have installed the Git version control system on your machine! You are ready to create repositories that will keep your code. We will do this in Setting up a Git repository section.

Installing JDK

As you already know, we will use Kotlin as our primary development language. However, we need Java installed on our system since Kotlin is executed on JVM. Open the Java JDK home page and chose the proper installation depending on the version of your OS: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.

The following platforms are supported:

  • Linux ARM 32 Hard Float ABI
  • Linux ARM 64 Hard Float ABI
  • Linux x86
  • Linux x86
  • Linux x64
  • Linux x64
  • macOS X
  • Solaris SPARC 64-bit
  • Solaris SPARC 64-bit
  • Solaris x64
  • Solaris x64
  • Windows x86
  • Windows x64

Follow the instructions depending on your OS version.

Microsoft Windows

The following are the steps to install JDK in Microsoft Windows:

  1. Download the proper executable for your version of Microsoft Windows
  2. Execute the downloaded file
  3. Follow the instructions

Linux

Here are the steps to install JDK in Linux:

  1. Download the proper RPM Package Manager (RPM) installation package for your platform.
  2. Open Terminal and install the package:
$ rpm -ihv package_you_downloaded.rpm
  1. Verify you have installed the Java version:
$ java -version

macOS

The following are the steps to install JDK in macOS:

  1. Download the dmg file for your macOS.
  2. Double-click on the dmg file to run it.
  3. Double-click on the PKG icon to launch the installation.
  4. Follow the installation instructions. Enter your system credentials if asked.
  5. Verify that the Java version from Terminal:
$ java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

Congratulations! Java is up and running! The next thing we are going to do is set up our IDE.

Installing the IDE

We chose IntelliJ IDEA as our IDE. Unfortunately, IDEA is not free. It is commercial software. You can buy a license or use IntelliJ IDEA Community Edition, Eclipse, or NetBeans to get it running. Follow the installation instructions for your specific OS.

Microsoft Windows

Linux

The following are the steps to install IDEA in Linux:

  1. Download IntelliJ IDEA from the JetBrains website: https://www.jetbrains.com/idea/download/#section=linux.
  2. Unpack the ideaIC.gz or ideaIU.gz file you have downloaded.
  3. Switch to the directory where you extracted IntelliJ IDEA.
  4. Execute the idea.sh script.

macOS

The following are the steps to install IDEA in macOS:

  1. Download IntelliJ IDEA from the JetBrains website: https://www.jetbrains.com/idea/download/#section=macos.
  2. Double-click the ideaIC.dmg or ideaIU.dmg file you have downloaded to mount the macOS disk image.
  3. Copy IntelliJ IDEA to the Applications folder.

Starting IntelliJ for the first time

You have installed IntelliJ; now it is time for the first run. You will be asked to do some configuring. Don't worry, everything is simple and easy. Just follow the instructions:

  1. Launch IntelliJ and wait until the Complete Installation dialog appears. Choose Don't import settings and continue by clicking on OK.

  1. Next, you will be prompted to select the UI theme. You can choose between the default theme and the Darcula theme. We recommend that you use the Darcula theme:
  1. In the next section, disable any plugins that are not required:
  1. In the next step, you are prompted to download additional plugins:
  1. Finally, you can start the project! The setup is complete, as shown in the following screenshot:

Installing Spring 5

Before installing or running Spring 5, we need to install Kotlin, since this is our primary programming language for the project:

  1. Open IntelliJ IDEA and choose Configure | Plugins, as shown in the following screenshot:
  1. In the search field, type Kotlin:
  1. Click on the Install JetBrains plugin... button.

  1. From the list that appears, choose Kotlin.
  2. If you do not already have Kotlin installed, you will see a green Install button. Click on it, otherwise click on the Update button, as shown in the following screenshot:
  1. Wait until the installation or update process completes:
  1. When the installation is finished, click on the Restart IntelliJ IDEA button:

If the Restart IntelliJ IDEA button does not restart your IDE, do it yourself manually.

Your IDE is ready for development. It is time to finally set up Spring 5! You can use Spring in the same way as any standard Java library. Simply include the appropriate Spring library files in your classpath. Spring does not require any special tool integration, so you can use any IDE or text editor! As you already know, we will stick to IntelliJ IDEA. You can run and debug Spring applications as you would any other Java application.

Spring can be used through Maven or Gradle. It is up to you to choose which suits you better. We will use Gradle in our development but we will give examples of Maven too.

Maven installation

The recommended way to get started using Spring Framework in your project is with a dependency management system. Take a look at the following Maven example:

<dependencies> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>5.0.0.RC4</version> 
    </dependency> 
</dependencies><repositories> 
    <repository> 
        <id>spring-milestones</id> 
        <name>Spring Milestones</name> 
        <url>https://repo.spring.io/libs-milestone</url> 
        <snapshots> 
            <enabled>false</enabled> 
        </snapshots>      
    </repository>  
</repositories>

Gradle installation

Gradle installation requires less code, as the following snippet shows:

repositories { 
    maven { 
        url 'https://repo.spring.io/libs-milestone' 
    } 
}  
dependencies { 
    compile 'org.springframework:spring-context:5.0.0.RC4' 
 
} 

Installing Postman

To try out our API calls, we will need Postman. Postman is a complete toolchain for API development. Postman is designed from the ground up to support the API developer. It offers us an intuitive user interface to send requests, save responses, add tests, and create workflows.

To get Postman, open https://www.getpostman.com/postman and choose your OS.

Microsoft Windows installation

The following are the steps to install Postman in Microsoft Windows:

  1. Download the setup file
  2. Run the installer
  3. Follow the setup instructions

Linux installation

To simplify the installation process, we recommend that you install it through the Google Chrome store. Search for Postman and install it:

macOS installation

Once you have downloaded the Postman-archived application, extract it, then drag the file to the Applications folder. Double-click on Postman to open the application.

Postman is installed. Run it and take a look at its UI. We will not go into details on how to use it. It is enough to play a bit. Most of the options are self-explanatory. Enjoy!

The following screenshot shows the Postman application running on macOS:

 

Setting up a Git repository

We have installed the IDE and Spring Framework. It is time to start working on our project. We will develop a REST application API for Notes and TODOs. This is a tool that everybody needs. We will give it a name: Journaler API. Journaler API will be a REST application capable of creating Notes and TODOs with reminders. Many different applications, such as mobile ones, will be synced to our backend instance running this REST application.

The first step in development is initializing a Git repository. Git will be our code versioning system. It is up to you to decide whether you will use GitHub, BitBucket, or something else for your remote Git instance. Create your remote repository and keep its URL ready along with your credentials. So, let's start!

The following are the steps to set up Git:

  1. Go into the directory containing the project.
  2. Execute the following command:
$ git init .
  1. The console output will be something like the following:
Initialized empty Git repository in <directory_you_choose/.git>
  1. We have initialized the repository. Now let's add the first file by executing the following command:
$ vi notes.txt
Here we are using vi editor to edit notes.txt. If you are familiar with some other editor, use that.
  1. Populate notes.txt with some content and save it.
  2. To add all of the relevant files, execute the following commands:
$ git add .
$ git commit -m "Journaler API: First commit"
  1. The console output will be something like the following:
[master (root-commit) 5e98ea4] Journaler API: First commit
 
1 file changed, 1 insertion(+)
 
create mode 100644 notes.txt
  1. Use the remote Git repository URL that you have prepared previously with credentials, and execute the following command:
$ git remote add origin <repository_url>
  • This sets the new remote.
  1. Execute the following command to verify the new remote URL:
$ git remote -v
  1. Finally, push everything we have to remote, by executing the following command:
$ git push -u origin master
  • If you are asked for credentials, enter them and confirm by pressing Enter.
 

Summary

These are exciting times! We are preparing to dive deep into the depths of Spring Framework. We are practically ready! We have set our environment up! We have installed Git, Java JDK, and IDE, shown you how Spring Framework is installed, and finally installed Postman. We skipped the MySQL installation for now but we will get back to it once we introduce you to Spring data.

Dear reader, we have come to the end of the first chapter. We have learned how to set up and configure the environment for development. In the next chapter, we will make our first real steps into Spring Framework. We will explain what Spring is and why you need it! We will write some code, run it, and trigger our first API call. So, get ready!

About the Author

  • Miloš Vasić

    Miloš Vasić is a software engineer, author and open source enthusiasts. Miloš holds a Bachelor degree in Programming of computer graphics and Master degree in the field of Android programming, both degrees he obtained at the Singidunum University. He published his first book Fundamental Kotlin in October 2016 and thus achieved his dream of becoming an author.

    Browse publications by this author

Latest Reviews

(1 reviews total)
This is a beautiful source. I want more.
Building Applications with Spring 5 and Kotlin
Unlock this book and the full library for FREE
Start free trial