Reader small image

You're reading from  Mastering Spring Cloud

Product typeBook
Published inApr 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781788475433
Edition1st Edition
Languages
Right arrow
Author (1)
Piotr Mińkowski
Piotr Mińkowski
author image
Piotr Mińkowski

Piotr works as a Solution Architect at Red Hat. He has several years of experience in software architecture and development. During this time, he was working in large organizations, where he was responsible for IT transformation to the modern cloud-native development approach. He is interested in technologies related to programming, containerization, and microservices. He writes about it in his blog https://piotrminkowski.com.
Read more about Piotr Mińkowski

Right arrow

Chapter 2. Spring for Microservices

I don't know many Java developers who have never touched Spring Framework. Actually, it consists of so many projects and can be used with many other frameworks that sooner or later you will be forced to try it. Although experiences with Spring Boot are rather less common, it has quickly gained a lot of popularity. In comparison with Spring Framework, Spring Boot is a relatively new solution. Its actual version is 2, instead of 5 for Spring Framework. What was the purpose of its creation? What is the difference between a running application with Spring Boot instead of the standard Spring Framework way?

Topics we will cover in this chapter include:

  • Using starters in order to enable additional features for the project
  • Using Spring Web library for implementing services that expose REST API methods
  • Customizing service configuration using properties and YAML files
  • Documenting and providing the specification for exposed REST endpoints
  • Configuring health checks and...

Introducing Spring Boot


Spring Boot is dedicated to running standalone Spring applications, the same as simple Java applications, with the java -jar command. The basic thing that makes Spring Boot different than standard Spring configuration is simplicity. This simplicity is closely related to the first important term we need to know about, which is a starter. A starter is an artifact that can be included in the project dependencies. It does nothing more than provide a set of dependencies to other artifacts that have to be included in your application in order to achieve the desired functionality. A package delivered in that way is ready for use, which means that we don't have to configure anything to make it work. And that brings us to the second important term related to Spring Boot, auto-configuration. All artifacts included by the starters have default settings set, which can be easily overridden using properties or other types of starters. For example, if you include spring-boot-starter...

Developing applications with Spring Boot


The recommended way to enable Spring Boot in your project is by using a dependency management system. Here, you can see a short snippet of how to include appropriate artifacts in your Maven and Gradle projects. Here is a sample fragment from the Maven pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

With Gradle, we do not need to define parent dependency. Here's a fragment from build.gradle:

plugins {
    id 'org.springframework.boot' version '1.5.7.RELEASE'
}
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.7.RELEASE")
}

When using Maven...

API Documentation


Swagger is the most popular tool for designing, building, and documenting RESTful APIs. It has been created by SmartBear, the designers of a very popular tool for SOAP Web Services, SoapUI. I think that might be sufficient recommendation for those who have long experience with SOAP. Anyway, with Swagger, we can design APIs using notation and then generate source code from it, or the other way around, where we start with the source code and then generate a Swagger file. With Spring Boot, we use the second option. 

Using Swagger 2 together with Spring Boot

The integration between Spring Boot and Swagger 2 is realized by the Springfox project. It examines application at runtime to infer API semantics based on Spring configurations, class structure, and Java annotations. To use Swagger in conjunction with Spring, we need to add the following two dependencies to the Maven pom.xml and annotate the main application class with @EnableSwagger2:

<dependency>
    <groupId>...

Spring Boot Actuator features


Just creating the working application and sharing standardized API documentation is not everything, especially if we are talking about microservices, where there are plenty of independent entities structuring one managed environment. The next important thing that needs to be mentioned is monitoring and gathering metrics from applications. In that aspect, Spring Boot also comes through. Project Spring Boot Actuator provides a number of built-in endpoints, which allow us to monitor and interact with the application. To enable it in our project, we should include spring-boot-starter-actuator in the dependencies. Here's a list of the most important Actuator endpoints:

Developer tools


Spring Boot offers some other useful tools for developers. The really cool thing for me is that the application is automatically restarted whenever files on the project classpath change. If you use Eclipse as your IDE, the only thing you have to do to enable it is to add the spring-boot-devtools dependency to the Maven pom.xml. Then, try to change something in one of your classes and save it. The application automatically restarts, and it takes much less than stopping and starting in the standard way. When I start our sample application, it takes about 9 seconds, and automatic restart takes only 3 seconds:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

We can exclude some resources if there is no need to trigger a restart when they are changed. By default, any file available on the classpath that points to a folder will...

Integrating application with database


You can find more interesting features described in the Spring Boot specification. I would like to spend more time describing other cool functionalities provided by that framework, but we should not go too far away from the main topic—Spring for microservices. As you may recall, through including embedded MongoDB in the project, I promised you a more advanced microservice example. Before starting to work on it, let's go back for a moment to the current version of our application. Its source code is available on my public GitHub account. Clone the following Git repository to your local machine: https://github.com/piomin/sample-spring-boot-web.git.

Building a sample application

The basic example is available in the master branch. The more advanced sample, with embedded MongoDB, is committed to the mongobranch. In case you would like to try running more advanced sample, you need to switch to that branch usinggit checkout mongo. Now, we need to perform some...

Running the application


Let's start MongoDB using the Docker run command:

docker run -d --name mongo -p 27017:27017 mongo

Something that may be useful for us is the Mongo database client. Using this, it is possible to create a new database and add some users with credentials. If you have Docker installed on Windows, the default virtual machine address is 192.168.99.100. The Mongo container has port 27017 exposed as a result of setting the -p parameter inside the run command. Well, in fact, we do not have to create the database because, when we provide the name while defining the client connection, it will automatically be created if it doesn't exist: 

Next, we should create a user for the application with sufficient authority:

Finally, we should set the Mongo database connection settings and credentials in the application.yml configuration file:

server: 
  port: ${port:2222}
spring: 
  application:
  name: first-service

// ...

---

spring:
  profiles: production
  application:
    name: first...

Summary


I have guided you through the process of single-microservice development, from a really basic example to a more advanced, production-ready Spring Boot application. I have described how to use starters to enable additional features for the project; use the Spring Web library to implement services that expose REST API methods; and then we moved on to customizing the service configuration using properties and YAML files. We also saw how to document and provide specifications for exposed REST endpoints. Next, we configured health checks and monitoring features. We used Spring Boot profiles to adapt the application to run in different modes and, finally, we used ORM features for interacting with embedded and remote NoSQL databases.

It's not an accident that I have not mentioned anything about Spring Cloud in this chapter. You just can't start using Spring Cloud projects without basic knowledge and experience in working with Spring Boot. Spring Cloud provides many different features that...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Spring Cloud
Published in: Apr 2018Publisher: PacktISBN-13: 9781788475433
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Piotr Mińkowski

Piotr works as a Solution Architect at Red Hat. He has several years of experience in software architecture and development. During this time, he was working in large organizations, where he was responsible for IT transformation to the modern cloud-native development approach. He is interested in technologies related to programming, containerization, and microservices. He writes about it in his blog https://piotrminkowski.com.
Read more about Piotr Mińkowski

Path

Description

/beans

Displays a full list of all the Spring beans initialized in the application.

/env

Exposes properties from Spring’s Configurable Environment, which means, for example, OS environment variables and properties from configuration files.

/health

Shows application health information.

/info...