Spring Boot Tutorial

In this spring boot tutorial, we are going to explain definitions, implementation guidance, and also how to develop spring applications. Learning this tutorial will help you to unleash your java framework application skill set. In the current market, it’s very difficult to manage built in applications, so finally, we have a spring boot application tool. We can say that this is one of the best IDE tools used now a day. There are much java based IDE tools available such as Eclipse, NetBeans, JDeveloper, and BlueJ. This blog may be helpful for those who want to change their career as a spring boot developer. So what you are waiting for, let’s get started on our journey;

What is the meaning of the spring boot tool?

Spring Boot is a type of IDE tool, which is mainly used to develop spring applications. We can also call it an Eclipse-based development application environment. This spring boot also offers a ready-to-use development environment to implement to debug, deploy, run, and deploy an application. The spring boot tool also helps to validate any application and quick fixes the application if any error occurs. The spring boot application is developed by software pivotal teams and used to build any stand-alone, and production-ready tools.

More popularly spring tool is known as an open-source java framework mainly used to create microservice applications. The best IDE tools used in spring boot are Eclipse, NetBeans, IntelliJ IDEA, BlueJ, and J developer.

The key features of Spring Boot:

Below are the major key features of the spring boot application:

1. Spring boot offers stand-alone spring applications with negligible efforts.

2. No code generation and no requirement for Extendable markup language (XML) configuration.

3. Also provides automatic configuration by creating sensible defaults.

4. Spring boot provides starter dependencies and starter PMOs.

5. Helps user to structure code as you like

6. Supports Gradle and Maven

7. Offers common non-functional production ready features for many Real-time applications such as;

  a. Security

   b. Metrics

   c. Health checks

   d. externalized configurations.

Spring boot Architecture:

The Spring Architecture will explain about components used, features, and also nature of the work. The below diagram explains the overall architectural design of spring boot;

IMAGE

Spring boot is a data module of the spring framework. This application tool is used to create stand-alone and production-grade Spring-based applications with minimum effort. Spring boot architecture is designed on the base of layered architecture where each layer in the spring communicates with the other.

The following are the different layers and classes present in the spring boot architecture.

1. Presentation layer

2. Business layer

3. Persistence layer

4. Database layer

Let me explain them one by one;

1. Presentation layer:

This presentation layer is used to handle the HTTP requests, translate the various JSON parameters to data objects, and also perform authenticates the requests, and transfer them to the business layer. This layer works as a ‘VIEW’ or frontend part.

2. Business layer:

The business layer used to handle business logic. This layer consists of several service classes and uses services offered by data access layers. This also performs activities like authorization and validation.

3. Persistence layer:

The persistence layer consists of all the storage logics and also translates the business objects from and to many database rows.

4. Database layer:

In this database layer user can able to work on methods like CRUD (create, retrieve, update, and delete) operations.

Spring Boot flow architecture:

Below is the diagram which will explain the data flow in spring boot architecture;

IMAGE

1. This flow architecture consists of validator classes, utility classes, and view classes.

2. Spring boot architecture uses the modules like Spring MVC, and spring data, etc. This spring boot architecture is the same as the spring MVC architecture. Here no need to create classes like DAO and DAOImpl classes.

3. Creates the data access layers and perform methods like CRUD.

4. This helps the client to make use of the HTTP requests like PUT and GET.

5. Here the request first reaches the controller, and the control maps ask for the requests. These requests also call the service logic if required.

6. In the service layer, all the business logic performs actions. This also helps to mapping of the data with model classes.

7. Java server page is returned to the user if you are unable to find any errors.

What is Micro service?

Microservice is an architecture that allows software developers to develop and deploy services independently. Each micro service runs on its own process and helps to achieve the lightweight model to support many business applications.

Advantages of Micro service:

These micro services offer the following advantages to the software developers:

1. Helps the developer to deploy the application easily.

2. Offers simple scalability and compatible with containers

3. Helps to achieve minimum configuration and time saving.

Spring Initializr: a complete detail

A spring Initializr is a web-based application tool developed by a pivotal software team. This type of spring initialzr helps developers to generate the spring boot project structure easily. This type of spring initilazr is used to create extensible API java-based projects. When you are working with metadata projects this initializr provides various options. This metadata model allows the developer to configure the list of dependencies that are supported by java virtual machine JVM and also various platform versions.

Spring Initializr modules:

Spring Initializr consists of the following modules;

1. Initializr- actuator: this module provides additional information and various statistics on project generations. This is an optional module.

2. Initializr-boom: in this module, there are lots of classes available, such as BOM stands for the bill of materials. This BOM is also a special kind of POM used to control the various versions of the project.

3. Initiliazr-docs: this type of module offers documentation.

4. Initializr-generator: this is a core project generation library.

5. Initializr-generator-spring: this also offers core generation libraries.

6. Initializr-generator-test: this module offers a test infrastructure for any project generation.

7. Initializr-metadata: this module provides metadata infrastructure for various aspects of the software projects.

8. Initializr-service-example: This provides the custom instances.

9. Initializr-version-resolver: this is an optional module that is used to extract the number of project versions from any arbitrary POM.

10. Initializr-web: this offers the web endpoints for third party clients.

The below diagram is an example of spring initiliazr UI:

IMAGE

Creating a project using spring initializr:

Before creating any project with spring initializr, a developer must be friendly with User Interface (UI). Below are a few UI labels:

1. Project: this project label defines the type of project. Here you can create either a Maven project or the Gradle project.

2. Language: Spring initializr supports various programming languages to work with, they are Java, Kotlin, and Groovy. By default, you will get Java language.

3. Spring Boot: Here you need to select the latest spring boot version. The latest version available is 2.2.2.

4. Project metadata: This metadata contains information related to any project, for example; Group or Artifact, etc. Here Group represents the package name, and Artifact represents the application name. The default group name available is com. Example and Artifact name would be Demo.

5. Dependencies: Dependencies are nothing but the collection of artifacts that you have to choose which one will be added to your project.

Important fields:

1. Name: it specifies the name of the artifact.

2. Description: in this field, you can write your own description of the project.

3. Package Name: This field is also similar to the group name.

4. Packaging: With the help of this field you have to choose the project packages. Here you have to select either Jar or War.

5. Java: here you can select the java virtual machine (JVM) version whichever you want to use. Now most commonly used java version is 8.0.

Spring Boot CLI:

The spring boot command line interface or CLI is a command-line interface tool and this is used to run the Groovy scripts. This is now considered one of the easiest ways to generate a spring boot with the help of the spring boot command-line interface. Here developer can create, run, or test the spring boot applications in command prompt.

In this section, I am going to explain the steps involved in the manual installation of the spring boot command-line interface:

Spring Boot Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Firstly you need to use the following link 

https://docs.spring.co/springboot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring boot.

Next, you need to download the spring command-line interface (CLI) distribution from the spring boot repository by using this link:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation.

To perform a manual installation, you need to below folders:

1. spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip

2. spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz.

Once you finish the download, you must unpack the archive file and follow the below steps in the given install.txt file. Sometimes this doesn’t require any type of environment setup.

In the Windows platform, all you need to do is go to the spring boot CLI bin directory ->in the command prompt. Now run the prompt command using the spring –version to make sure the spring CLI is installed correctly. Once you finish executing this command, now you can see the spring boot CLI version as shown below;

spring boot CLI bin directory                                         

Run Hello World using Groovy:

Create a simple groovy program file this contains the REST endpoint script and run this groovy file with the help of spring boot CLI. The below code explains this scenario:

@Controller

Class Example1

{

@RequestMapping (“/”)

@ResponseBody

  Public String Hello ()

  {

      “HELLO Spring Boot”

}

}

Next step you have to save the groovy file with the name hello. groovy.

Note: In the above program example, we have saved the groovy file inside the spring boot command line interface CLI bin directory.

Now you have to run the application by using the command like spring run hello. groovy as shown in the below diagram.

 interface CLI bin directory

Once you run the hello world groovy file, then the required dependencies will download automatically. This dependency will start the application in Tomcat 8080 port as shown in the below diagram;

application in Tomcat 8080 port

Once the Tomcat starts, you need to go to the web browser by using URL http://localhost:8080/.

Command-Line properties:

Spring boot application is used to convert the command line properties into spring boot environment setup properties. Command-line properties always work on the basis of property sources. Spring boot uses the port number 8080 to start the Tomcat application by default.

Properties file:

Properties files are used to keep the “n” number of command line properties in a single file. This type of single file is used to run the application in a different environmental setup.

Generally, in the spring boot, command-line properties are kept in the application. Properties file under the server classpath.  This application. The properties file is located in the directory src/main/resources. The following code explains this property;

Server.port = 9090 // server port number

Spring.application.name = demoservice.

YAML file:

The spring boot application offers YAML based configuration property to run the application. Here instead of using the application. Properties, we can also use application.yml [YAML file]. This type of YAML file should be kept in the classpath.

Externalized properties:

We usually keep the properties under classpath files; we can also keep them in different location or path file. Once you run the JAR file, we can define the properties file path. The below command explains this;

-Dspring.config.location = C: \application.properties

Subscribe to our youtube channel to get new updates..!

Spring Boot –Code structure:

I said earlier, the spring boot architecture framework does not contain any code layout to work with. But below are a few examples that will give a brief idea about code structure.

1. Default package code structure:

As we know that a class that does not hold any type of package declaration is now considered as a default package. Point to be noted here that in general, a default package declaration is not recommended while writing code. In spring boot, the default package may cause severe issues namely Auto configuration and Component scan.

Note: In java default package can be used as a naming convention to reverse any domain name.

2. Typical Layout:

The typical layout for the spring boot application is shown below image;

IMAGE

Here the application.java file will declare the main method with the help of @SpringbootApplication.  

Code as follows:

@SpringBootApplication

Public class Application

  {

  Public static void main (string [] args)

   {

    springApplication.run (Application. Class, args);

    }

}

Spring Boot- Actuator

Spring boot actuator offers secured endpoints to monitor and manage the spring boot applications. In the spring boot application environment, all the actuator endpoints are secured.

Enabling spring boot Actuator:

To enable any type of spring boot actuator to your spring boot application, all you need to do is that adding the spring boot starter actuator dependency to build the configuration files.

If you are maven user, you can add the below dependencies in your pom.xml file:



  < groupId>org. springFramework.boot

   spring-boot-starter-actuator

If you are a Gradle user, you can add the below dependencies to build your Gradle file;

Compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-actuator’

In the spring boot application property file, you must disable the security for actuator endpoints.

Management.security.enabled = false

If you are a YAML file, you can add the following property in the application .yml file.

Management:

   Security:

Enabled: false

For Maven, you have to use the following command;

mvn clean Install

Once you successfully built the configuration file, then you are able to find the JAR file under the spring boot target directory. For the Gradle file, you have to use the below command;

gradle clean build

Now run the JAR files by using the below command:

JAVA –jar

The application has started on the TOMCAT 8080 port number. Some important spring boot actuator endpoints are listed below.

Endpoints and its usage:

/metrics : this is used to view the various applications metrics such as memory free, system update, threads, classes, and memory used etc.

/env  : this is used to view the list of different environment variables used in spring boot applications.

/beans : this is used to view the spring beans application types, dependencies, and scopes.

/health: this is used to view the applications health.

/info : this is used to view all kinds of information about the spring boot application environment.

/trace : to view the list of traces related to your REST endpoints. 

Running Spring boot application with MiniKube:

Here we are going to explain the installation process, developing a spring boot application using minikube, set up an application with the help of a one-node cluster, and deploy the application using configuration files.

Let me explain them one by one;

1. Installation of Minikube software:

This installation of minikube software consists of three major steps;

a. Installing hypervisor (same as the virtual box).

b. Command-line interface Kubectl.

c. set up spring boot application using Minikube

First, we will start by installing Minikube software by using the following syntax:

$> minikube start

$> minikube config set VM-driver Virtualbox

$> kubectl config use-context minikube

After this method, now we can verify the kubectl communicates with our cluster;

$> Kubectl cluster-info

The final output should look like this:

Kubernetes is running at this weblink HTTPS: //192.168.99.100.8443

If you want to debug and diagnose the cluster problems by using this method:

‘kubectl cluster-info dump’.

Finally, you can inspect the state of the cluster with the help of this command;

$> minikube dashboard

Deployment using spring boot imperative commands:

Here we are going to create a deployment for any backend application. Below are the important steps to be used while performing deployment:

1. Creating the deployment:

Here we are going to use Kubectl by passing the required commands as arguments:

$> kubectl run demo-backend –image = demo-backend: latest \

---port = 8080 –image-pull-policy Never  //this is tomcat port number

Here –port defines the deployment port number 8080 using the pods.

The flag –image-pull-policy defines how to pull the image from the minikube registry.

2. Verifying the deployment:

With the help of the below command, you can check whether the successfully done or not.

$> kubectl get deployments

The output looks like this:

Name                   DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE

Demo-backend        1             1            1              1              19s

The pod ID will look like this;

$> kubectl get pods

$> kubectl logs

3. Creating a service for the deployment:

If you want to make the REST endpoint of your backend application, first you need to create a service;

$> kubectl expose deployment demo-backend   --type = NodePort

Where –type = Nodeport specifies the service which is available from the outside cluster. This service will be available at : . The map requests incoming service at to port number 8080.

With the help of the below command, you can check whether you have successfully requested the incoming service or not

$> kubectl get services

The output looks like this:

Name                                           Type         CLUSTER-IP     EXTERNAL_IP      PORT(s)            AGE

Demo-backend   Nodeport    10.106.11.133               8080:30117/TCP  

11

Calling the service:

Here, you can call your backend service for the first time with the help of the below command;

$> minikube service demo-backend

The above command will start your default browser, and opens the command prompt like : .

Cleaning up service and deployment:

By using these commands you can remove service and deployment:

$> kubectl delete service demo-backend

$> kubectl delete deployment demo-backend

Spring Boot – OAUTH2 with JWT

In this section, we are going to explain spring boot security mechanisms and OAuth2 with JWT.

a. Authorization server:

The authorization server is a popular architectural component for web-based Application programming interface (API) security. This type of Authorization server acts as a centralization authorization system that allows your applications and HTTP endpoints to identify the features of the applications.

b. Resource Server:

The resource server is a type of application that offers the access token to the clients and enables them to access the resource server Hypertext transfer protocol or HTTP endpoints. This resource server is a collection of libraries, which contains resources like HTTP endpoint, Static resources, and Dynamic web pages.

c.OAuth2:

OAuth2 is an authorization framework that enables your application of web security to access the resources from the end-clients. If you want to build an OAuth2 application, you must focus on the Grant type (authorization code), client ID, and Client Secret.

JWT Token:

JWT token is a Java script object notation (JSON) web token, used to specify the secured claims between any two parties. If you are going to build an OAuth2 application that enables the use of Authorization server, Resource server, and tokens.

Here I am going to explain a few token files which are used to perform OAuthe2 authorization server;

1. Spring boot starter security: This type of token is used to implement spring security.

2. Spring Security OAUTH2: This token type is used to implement the OAUTH2 structure to enable the authorization server and resource server.

3. Spring Security JWT: this token file is used to generate the JWT token for web security systems.

4. Spring Boot starter JDBC: this type of token file is used to access the database to ensure that whether the user is available or not.

5. Spring Boot starter Web: this is used to write HTTP endpoints.

6. H2 Database: this token file stores the user information mainly used for authentication and authorization purpose.

Differences between Sprint boot and Spring MVC:

In this section, I am going to explain the major differences between spring boot and Spring MVC:

1. Spring boot:

a. Spring boot always tries to avoid the boiler plate and wraps different dependencies together within a single unit. For example spring boot starter web application.

b. spring boot methods and files are packaged as a jar with the embedded server by default.

c. helps to reduce the development time and increases productivity so that production ready application can be built quickly.

2. Spring MVC:

a. Spring MVC takes more time in productivity as each and every dependency is executed separately.

b. In spring MVC, a lot of configurations to be written to achieve this.

c. Time consumption is more when compared to Spring boot and error-prone dependency actions also done when the configuration between any two versions won’t match.

Drawbacks of Spring Boot:

Following are the very important drawbacks of the spring boot framework application:

1. High learning curve needed when you decided to work with the spring boot framework.

2. Complex to implement if it’s a big project.

3. Tons of parallel mechanisms needed.

4. Lots of XML needed in spring boot.

5. Lack of guidelines.

Spring Boot Training

Weekday / Weekend Batches

Conclusion:

In this blog, I have tried to explain the spring boot tutorial along with the definition, configuration, authorization, and code structure. From this tutorial, you will be able to learn the overall structure of the spring boot and its advantages. I can say that you will learn the only theoretical part, if you want to gain some hands-on experience; you need to take the online course. Our technical support team provides 24/7 online support for any course-related queries.

 

Find our upcoming Spring Boot Training Online Classes

  • Batch starts on 30th Jul 2021, Fast Track batch

  • Batch starts on 3rd Aug 2021, Weekday batch

  • Batch starts on 7th Aug 2021, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Webinar

Python tutorial for beginners

5th April | 08:00 AM

150 Registered

Manikanth
Manikanth
Research Analyst
As a Senior Writer for HKR Trainings, Sai Manikanth has a great understanding of today’s data-driven environment, which includes key aspects such as Business Intelligence and data management. He manages the task of creating great content in the areas of Digital Marketing, Content Management, Project Management & Methodologies, Product Lifecycle Management Tools. Connect with him on LinkedIn and Twitter.