<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Yogesh Mali</title>
    <description>The latest articles on DEV Community by Yogesh Mali (@betterjavacode).</description>
    <link>https://dev.to/betterjavacode</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F383451%2F0132110e-2cc0-4052-898d-f4b55c166e1c.jpg</url>
      <title>DEV Community: Yogesh Mali</title>
      <link>https://dev.to/betterjavacode</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/betterjavacode"/>
    <language>en</language>
    <item>
      <title>Upload File to S3 Using NestJS Application</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sun, 07 Jan 2024 04:30:20 +0000</pubDate>
      <link>https://dev.to/betterjavacode/upload-file-to-s3-using-nestjs-application-3hd3</link>
      <guid>https://dev.to/betterjavacode/upload-file-to-s3-using-nestjs-application-3hd3</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this post, I will show how to upload a file to S3 using a NestJS application and Multer. S3 is Amazon's Simple Storage Service (S3). In old systems, one could upload files to a database. However, with storage services, it is easier to upload and retrieve files. This is also more performant.&lt;/p&gt;

&lt;p&gt;If you are a beginner with the NestJS framework, I would recommend reading their documentation. I have written some posts about NestJS previously here, here, and here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simple Storage Service
&lt;/h2&gt;

&lt;p&gt;Simple storage service is also known as S3. Irrespective of what kind of application you build, you have to store static files somewhere. AWS offers a simple and effective service called S3. As previously mentioned in the post, application developers used to save files in the database, but that is not very performant.&lt;/p&gt;

&lt;p&gt;With S3, now you can store the file in a storage service and create a file link that you can save in the database.&lt;/p&gt;

&lt;p&gt;To understand S3 is to understand a hash table. Usually, when you store any file on S3, the service generates a random string as a key to identify that file. The file is the blob format data.&lt;/p&gt;

&lt;p&gt;S3 is targeted towards application builders to individual users. The advantages of S3 are scalability, high availability, performance, and security. S3 can also be used for redundancy. One thing to remember is that you can not use S3 to host a static website, especially if you want to use it with HTTPS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting up an S3 bucket
&lt;/h3&gt;

&lt;p&gt;For this demo, let's set up an S3 bucket in the AWS S3 service. I would assume that you have an AWS account with enough permissions to manage resources like creating or deleting buckets. If you don't, you can always create an account for AWS with a free tier. Over the years, AWS has done a great job to help developers play with their services and improve them.&lt;/p&gt;

&lt;p&gt;Once you have your user, make sure to download the AWS Access Key and AWS Secret Key. We will need these keys to call AWS services programmatically.&lt;/p&gt;

&lt;p&gt;Let's create a bucket in S3.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i6Sc9h81--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6eh0ooeps46bylny99ap.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i6Sc9h81--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6eh0ooeps46bylny99ap.JPG" alt="S3 Bucket Creation" width="800" height="669"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  NestJS Application
&lt;/h2&gt;

&lt;p&gt;Let's create a nestjs application. If you do not have nest-cli downloaded, I would recommend use &lt;code&gt;npm i @nestjs/cli&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Set up Application
&lt;/h3&gt;

&lt;p&gt;Create a new application&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nest new fileuploaddemo&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once we have the facade of the application, we will create an API, service, and a database table. If you are wondering, why a database table, then to answer that - We will use a database to store file metadata information including the link and when it was created.&lt;/p&gt;

&lt;p&gt;Just like previous articles, we will use prisma as our ORM for creating this nestjs application.&lt;/p&gt;

&lt;p&gt;Install Prisma dependencies&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install prisma --save-dev&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install @prisma/client&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create initial Prisma set up&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx prisma init&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you are using Windows environment, you might run into an error while running above command. So set environment variables&lt;/p&gt;

&lt;p&gt;&lt;code&gt;set PRISMA_CLI_QUERY_ENGINE_TYPE=binary&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;set PRISMA_CLIENT_ENGINE_TYPE=binary&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Add the database table details in &lt;code&gt;schema.prisma&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model FileEntity {
  id Int @default(autoincrement()) @id
  fileName String
  fileUrl  String 
  key      String
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And make sure to set &lt;code&gt;DATABASE_URL&lt;/code&gt;as the environment variable before running Prisma migrations.&lt;/p&gt;

&lt;p&gt;Run prisma migrations&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm prisma migrate dev&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Set up environment
&lt;/h3&gt;

&lt;p&gt;We will need a few environment variables to make sure our application is functioning.&lt;/p&gt;

&lt;p&gt;So create .env file in your application and add the following variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=accessKey
AWS_SECRET_ACCESS_KEY=secretKey
AWS_BUCKET_NAME='nestjsfileuploaddemo'
DATABASE_URL="mysql://user:password@localhost:3306/fileuploaddemo?schema=public"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Upload API
&lt;/h3&gt;

&lt;p&gt;Usually, a client application will send us file details through form-data. For this demo, we will create an API that the client application can call. This will be our upload API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Controller, Post, UploadedFile, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { FileUploadService } from "src/services/fileupload.service";
import { Express } from 'express';


@Controller('/v1/api/fileUpload')
export class FileController {
    constructor(private fileUploadService: FileUploadService) {}

    @Post()
    @UseInterceptors(FileInterceptor('file'))
    async uploadFile(@UploadedFile() file: Express.Multer.File): Promise {
        const uploadedFile = await this.fileUploadService.uploadFile(file.buffer, file.originalname);
        console.log('File has been uploaded,', uploadedFile.fileName);        
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this API, we are using FileInterceptor from NestJS which extracts file details from the request.&lt;/p&gt;

&lt;p&gt;The API is straightforward. We pass the file metadata information to FileUploadService and that does the job of uploading the file to S3 as well as saving the data in the database.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. FileInterceptor for File Upload
&lt;/h3&gt;

&lt;p&gt;An interceptor is one of the fundamental concepts in NestJS. Interceptor is a class with annotation @Injectable() and implements NestInterceptor interface.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qKe_4PXd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmp4hwxkm43m0iz52vvw.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qKe_4PXd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmp4hwxkm43m0iz52vvw.JPG" alt="Interceptor in NestJS" width="800" height="259"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Create a FileUploadService
&lt;/h3&gt;

&lt;p&gt;FileUploadService will perform two tasks. One is to upload the file to S3 and the second is to store the metadata in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { FileEntity, Prisma } from "@prisma/client";
import { S3 } from "aws-sdk";
import { PrismaService } from "src/common/prisma.service";
import { v4 as uuid } from 'uuid';

@Injectable()
export class FileUploadService {
    constructor(private prismaService: PrismaService,
        private readonly configService: ConfigService,){}

    async uploadFile(dataBuffer: Buffer, fileName: string): Promise {
        const s3 = new S3();
        const uploadResult = await s3.upload({
            Bucket: this.configService.get('AWS_BUCKET_NAME'),
            Body: dataBuffer,
            Key: `${uuid()}-${fileName}`,
        }).promise();

        const fileStorageInDB = ({
            fileName: fileName,
            fileUrl: uploadResult.Location,
            key: uploadResult.Key,
        });

        const filestored = await this.prismaService.fileEntity.create({
            data: fileStorageInDB
        });

        return filestored;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a method called uploadFile in this service class. It takes two parameters one for a data buffer and the other for a file name.&lt;/p&gt;

&lt;p&gt;We create an S3 instance using S3() and use that to upload files to S3. It needs a bucket name, a data buffer in the body, and a unique key for storing the file.&lt;/p&gt;

&lt;p&gt;We use the location as fileUrl from the uploaded file. And then save the metadata information in the database.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Final Demo
&lt;/h3&gt;

&lt;p&gt;Let's run our application to see how it is working now.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm run start&lt;/code&gt; - will start the application at default port 3000.&lt;/p&gt;

&lt;p&gt;We will use postman to call our upload API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EmzzhhU1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jvds28jm8knq60tnc64p.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EmzzhhU1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jvds28jm8knq60tnc64p.JPG" alt="File Upload API" width="800" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once we upload the file, we will see a console message of file uploaded.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--VLqOcgCt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7rdgafx2fmwglokzghe.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--VLqOcgCt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7rdgafx2fmwglokzghe.JPG" alt="NestJS Console Messsage for File Upload" width="800" height="193"&gt;&lt;/a&gt;&lt;br&gt;
And similarly, a database entry&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EzAak1ME--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42jhpkzpjnwsswhlhhaw.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EzAak1ME--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42jhpkzpjnwsswhlhhaw.JPG" alt="Database Entry for File Upload" width="800" height="73"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Just to make sure that we have our files uploaded in S3, let's look at the bucket.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yKpA-jsA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dstzt33tnw9ng2bhdj89.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yKpA-jsA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dstzt33tnw9ng2bhdj89.JPG" alt="AWS S3 List of Files" width="800" height="92"&gt;&lt;/a&gt;&lt;br&gt;
You will see two entries in the bucket.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, we discussed how we can upload a file to AWS Simple Storage Service (S3) using NestJS application. We only covered the surface of this vast topic of S3. You can also manage to upload private files, encrypt, and decrypt those files. You can also subscribe to events of file upload. There are a lot of options when it comes to AWS S3.  We will cover more in the upcoming series of NestJS applications.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>s3</category>
      <category>nestjs</category>
      <category>multer</category>
    </item>
    <item>
      <title>How to use Circuit Breaker in a Spring Boot Application</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sat, 27 Feb 2021 06:31:12 +0000</pubDate>
      <link>https://dev.to/betterjavacode/how-to-use-circuit-breaker-in-a-spring-boot-application-1mp</link>
      <guid>https://dev.to/betterjavacode/how-to-use-circuit-breaker-in-a-spring-boot-application-1mp</guid>
      <description>&lt;p&gt;In this post, I will show how we can use the Circuit Breaker pattern in a Spring Boot Application. When I say Circuit Breaker pattern, it is an architectural pattern. Netflix had published a library Hysterix for handling circuit breakers.  As part of this post, I will show how we can use a circuit breaker pattern using the resilence4j  library in a Spring Boot Application.&lt;/p&gt;

&lt;p&gt;In other news, I recently released my book &lt;a href="https://betterjavacode.com/programming/simplifying-spring-security" rel="noopener noreferrer"&gt;Simplifying Spring Security&lt;/a&gt;. If you are interested to learn about Spring Security, you can buy it &lt;a href="https://gumroad.com/l/VgSdH" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Circuit Breaker?
&lt;/h2&gt;

&lt;p&gt;The concept of Circuit Breaker comes from Electrical Engineering. In most electricity networks, circuit breakers are switches that protect the network from damage caused by an overload of current or short circuit.&lt;/p&gt;

&lt;p&gt;Similarly, in software, a circuit breaker stops the call to a remote service if we know the call to that remote service is either going to fail or time out. The advantage of this is to save resources and being proactive in our troubleshooting of the remote procedure calls.&lt;/p&gt;

&lt;p&gt;The circuit breaker makes the decision of stopping the call based on the previous history of the calls. But there are alternative ways how it can handle the calls. Usually, it will keep track of previous calls. Suppose 4 out of 5 calls have failed or timed out, then the next call will fail. This helps to be more proactive in handling the errors with calling service and caller service can handle the response in a different way, allowing users to experience the application differently than an error page.&lt;/p&gt;

&lt;p&gt;Another way circuit breaker can act if calls to remote service are failing in a particular time duration.  A circuit breaker will open and will not allow the next call till remote service improves on error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resilience4J Library
&lt;/h2&gt;

&lt;p&gt;We have our code where we call remote service. The circuit breaker module from &lt;code&gt;resilience4j&lt;/code&gt; library will have a lambda expression for a call to remote service OR a supplier to retrieve values from the remote service call. I will show this as part of the example. The circuit breaker decorates this remote service call in such a way so it can keep track of responses and switch states.&lt;/p&gt;

&lt;h3&gt;
  
  
  Different configurations of Resilience4j Library
&lt;/h3&gt;

&lt;p&gt;To understand the circuit breaker concept, we will look at different configurations this library offers.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;slidingWindowType()&lt;/code&gt; – This configuration basically helps in making a decision on how the circuit breaker will operate. There are two types COUNT_BASED and TIME_BASED. COUNT_BASED circuit breaker sliding window will take into account the number of calls to remote service while TIME_BASED circuit breaker sliding window will take into account the calls to remote service in a certain time duration.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;failureRateThreshold()&lt;/code&gt; – This configures the failure rate threshold in percentage. If x percentage of calls are failing, then the circuit breaker will open.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;slidingWindowSize()&lt;/code&gt; – This setting helps in deciding the number of calls to take into account when closing a circuit breaker.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;slowCallRateThreshold()&lt;/code&gt; – This configures the slow call rate threshold in percentage. If x percentage of calls are slow, then the circuit breaker will open.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;slowCallDurationThreshold&lt;/code&gt; – Time duration threshold about which calls are considered slow.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;minimumNumberOfCalls()&lt;/code&gt; – Minimum number of calls required before which circuit breaker can calculate the error rate.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ignoreException()&lt;/code&gt; – This setting allows you to configure an exception that a circuit breaker can ignore and will not count towards success or failure of call of remote service.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;waitDurationInOpenState()&lt;/code&gt; – Duration for which the circuit breaker should remain in the open state before transitioning into a half-open state.  The default value is 60 seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  Count-Based Circuit Breaker
&lt;/h2&gt;

&lt;p&gt;While using &lt;code&gt;resilience4j&lt;/code&gt; library, one can always use default configurations that the circuit breaker offers. Default configurations are based on the COUNT-BASED sliding window type.&lt;/p&gt;

&lt;p&gt;So how do we create a circuit breaker for COUNT-BASED sliding window type?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()               .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED).slidingWindowSize(10)
    .slowCallRateThreshold(65.0f)
    .slowCallDurationThreshold(Duration.ofSeconds(3))
    .build();

CircuitBreakerRegistry circuitBreakerRegistry =
                CircuitBreakerRegistry.of(circuitBreakerConfig);

CircuitBreaker cb = circuitBreakerRegistry.circuitBreaker("BooksSearchServiceBasedOnCount");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we are creating a circuit breaker configuration that includes sliding window of type &lt;code&gt;COUNT_BASED&lt;/code&gt;. This circuit breaker will record the outcome of 10 calls to switch circuit breaker to the closed state.  If 65 percent of calls are slow with slow being of duration of more than 3 seconds, the circuit breaker will open.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;CircuitBreakerRegistry&lt;/code&gt; is a factory to create a circuit breaker.&lt;/p&gt;

&lt;h2&gt;
  
  
  Time-Based Circuit Breaker
&lt;/h2&gt;

&lt;p&gt;Now on Time-Based circuit breaker.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()                .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.TIME_BASED)             .minimumNumberOfCalls(3)
                .slidingWindowSize(10)
                .failureRateThreshold(70.0f)
                .build();

CircuitBreakerRegistry circuitBreakerRegistry =
                CircuitBreakerRegistry.of(circuitBreakerConfig);

CircuitBreaker cb = CircuitBreakerRegistry.circuitBreaker("BookSearchServiceBasedOnTime");

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we are creating a circuit breaker configuration that includes a sliding window of type TIME_BASED. Circuit breaker will record the failure of calls after a minimum of 3 calls.  If 70 percent of calls fail, the circuit breaker will open.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example of Circuit Breaker in Spring Boot Application
&lt;/h2&gt;

&lt;p&gt;We have covered the required concepts about the circuit breaker. Now, I will show we can use a circuit breaker in a Spring Boot application.&lt;/p&gt;

&lt;p&gt;On one side, we have a REST application &lt;code&gt;BooksApplication&lt;/code&gt; that basically stores details of library books. On the other side, we have an application &lt;code&gt;Circuitbreakerdemo&lt;/code&gt; that calls the REST application using RestTemplate. We will decorate our REST call through the circuit breaker.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;BooksApplication&lt;/code&gt; stores information about books in a MySQL database table &lt;code&gt;librarybooks&lt;/code&gt;. The REST Controller for this application has &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;POST&lt;/code&gt; methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
package com.betterjavacode.books.controllers;

import com.betterjavacode.books.daos.BookDao;
import com.betterjavacode.books.models.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@CrossOrigin("https://localhost:8443")
@RestController
@RequestMapping("/v1/library")
public class BookController
{
    @Autowired
    BookDao bookDao;

    @GetMapping("/books")
    public ResponseEntity&amp;lt;List&amp;gt; getAllBooks(@RequestParam(required = false) String bookTitle)
    {
        try
        {
            List listOfBooks = new ArrayList&amp;lt;&amp;gt;();
            if(bookTitle == null || bookTitle.isEmpty())
            {
                bookDao.findAll().forEach(listOfBooks::add);
            }
            else
            {
                bookDao.findByTitleContaining(bookTitle).forEach(listOfBooks::add);
            }

            if(listOfBooks.isEmpty())
            {
                return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NO_CONTENT);
            }

            return new ResponseEntity&amp;lt;&amp;gt;(listOfBooks, HttpStatus.OK);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/books/{id}")
    public ResponseEntity getBookById(@PathVariable("id") long id)
    {
        try
        {
            Optional bookOptional = bookDao.findById(id);

            return new ResponseEntity&amp;lt;&amp;gt;(bookOptional.get(), HttpStatus.OK);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/books")
    public ResponseEntity addABookToLibrary(@RequestBody Book book)
    {
        try
        {
            Book createdBook = bookDao.save(new Book(book.getTitle(), book.getAuthor(),
                    book.getIsbn()));
            return new ResponseEntity&amp;lt;&amp;gt;(createdBook, HttpStatus.CREATED);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/books/{id}")
    public ResponseEntity updateABook(@PathVariable("id") long id, @RequestBody Book book)
    {
        Optional bookOptional = bookDao.findById(id);

        if(bookOptional.isPresent())
        {
            Book updatedBook = bookOptional.get();
            updatedBook.setTitle(book.getTitle());
            updatedBook.setAuthor(book.getAuthor());
            updatedBook.setIsbn(book.getIsbn());
            return new ResponseEntity&amp;lt;&amp;gt;(bookDao.save(updatedBook), HttpStatus.OK);
        }
        else
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/books/{id}")
    public ResponseEntity deleteABook(@PathVariable("id") long id)
    {
        try
        {
            bookDao.deleteById(id);
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NO_CONTENT);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the other side, our application &lt;code&gt;Circuitbreakerdemo&lt;/code&gt; has a controller with thymeleaf template so a user can access the application in a browser.&lt;/p&gt;

&lt;p&gt;For the demo purpose, I have defined CircuitBreaker in a separate bean that I will use in my service class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Bean
    public CircuitBreaker countCircuitBreaker()
    {
        CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
                .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
                .slidingWindowSize(10)
                .slowCallRateThreshold(65.0f)
                .slowCallDurationThreshold(Duration.ofSeconds(3))
                .build();

        CircuitBreakerRegistry circuitBreakerRegistry =
                CircuitBreakerRegistry.of(circuitBreakerConfig);

        CircuitBreaker cb = circuitBreakerRegistry.circuitBreaker("BooksSearchServiceBasedOnCount");

        return cb;
    }

    @Bean
    public CircuitBreaker timeCircuitBreaker()
    {
        CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
                .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.TIME_BASED)
                .minimumNumberOfCalls(3)
                .slidingWindowSize(10)
                .failureRateThreshold(70.0f)
                .build();

        CircuitBreakerRegistry circuitBreakerRegistry =
                CircuitBreakerRegistry.of(circuitBreakerConfig);

        CircuitBreaker cb = circuitBreakerRegistry.circuitBreaker("BookSearchServiceBasedOnTime");
        return cb;
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have defined two beans one for the count-based circuit breaker and another one for time-based.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;BookStoreService&lt;/code&gt; will contain a calling &lt;code&gt;BooksApplication&lt;/code&gt; and showing books that are available. This service will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller
public class BookStoreService
{

    private static final Logger LOGGER = LoggerFactory.getLogger(BookStoreService.class);

    @Autowired
    public BookManager bookManager;

    @Autowired
    private CircuitBreaker countCircuitBreaker;

    @RequestMapping(value = "/home", method= RequestMethod.GET)
    public String home(HttpServletRequest request, Model model)
    {
        return "home";
    }

    @RequestMapping(value = "/books", method=RequestMethod.GET)
    public String books(HttpServletRequest request, Model model)
    {
        Supplier&amp;lt;List&amp;gt; booksSupplier =
                countCircuitBreaker.decorateSupplier(() -&amp;gt; bookManager.getAllBooksFromLibrary());

        LOGGER.info("Going to start calling the REST service with Circuit Breaker");
        List books = null;
        for(int i = 0; i &amp;lt; 15; i++)
        {
            try
            {
                LOGGER.info("Retrieving books from returned supplier");
                books = booksSupplier.get();
            }
            catch(Exception e)
            {
                LOGGER.error("Could not retrieve books from supplier", e);
            }
        }
        model.addAttribute("books", books);

        return "books";
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So when the user clicks on the books page, we retrieve books from our BooksApplication REST Service.&lt;/p&gt;

&lt;p&gt;I have autowired the bean for &lt;code&gt;countCircuitBreaker&lt;/code&gt;. For demo purposes – I will be calling the REST service 15 times in a loop to get all the books. This way, I can simulate interruption on my REST service side.&lt;/p&gt;

&lt;p&gt;Our circuit breaker decorates a supplier that does REST call to remote service and the supplier stores the result of our remote service call.&lt;/p&gt;

&lt;p&gt;In this demo, we are calling our REST service in a sequential manner, but remote service calls can happen parallelly also. The circuit breaker will still keep track of results irrespective of sequential or parallel calls.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;Let’s look at how the circuit breaker will function in a live demo now. My REST service is running on port 8443 and my Circuitbreakerdemo application is running on port 8743.&lt;/p&gt;

&lt;p&gt;Initially, I start both of the applications and access the home page of &lt;code&gt;Circuitbreakerdemo&lt;/code&gt; application. The home page contains the link for viewing all the books from the store.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgds181ikl0q7t0ggalqy.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgds181ikl0q7t0ggalqy.JPG" alt="Circuit Breaker in a Spring Boot Application - Home Page"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now to simulate some errors, I have added the following code in my RestTemplate call that basically sleeps for 3 seconds before returning the result of the REST call.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public List getAllBooksFromLibrary ()
    {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        ResponseEntity&amp;lt;List&amp;gt; responseEntity;
        long startTime = System.currentTimeMillis();
        LOGGER.info("Start time = {}", startTime);
        try
        {
            responseEntity= restTemplate.exchange(buildUrl(),
                    HttpMethod.GET, null, new ParameterizedTypeReference&amp;lt;List&amp;gt;()
                    {});
            if(responseEntity != null &amp;amp;&amp;amp; responseEntity.hasBody())
            {
                Thread.sleep(3000);
                LOGGER.info("Total time to retrieve results = {}",
                        System.currentTimeMillis() - startTime);
                return responseEntity.getBody();
            }
        }
        catch (URISyntaxException | InterruptedException e)
        {
            LOGGER.error("URI has a wrong syntax", e);
        }

        LOGGER.info("No result found, returning an empty list");
        return new ArrayList&amp;lt;&amp;gt;();
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In short, my circuit breaker loop will call the service enough times to pass the threshold of 65 percent of slow calls that are of duration more than 3 seconds. Once I click on the link for here, I will receive the result, but my circuit breaker will be open and will not allow future calls till it is in either half-&lt;code&gt;open&lt;/code&gt; state or &lt;code&gt;closed&lt;/code&gt; state.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkxcz0dwzc13g5homqmzn.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkxcz0dwzc13g5homqmzn.JPG" alt="Circuit Breaker in a Spring Boot Application - Initial Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You will notice that we started getting an exception CallNotPermittedException when the circuit breaker was in the OPEN state. Also, the circuit breaker was opened when the 10 calls were performed. This is because our sliding window size is 10.&lt;/p&gt;

&lt;p&gt;Another way, I can simulate the error by shutting down my REST service or database service. That way REST calls can take longer than required.&lt;/p&gt;

&lt;p&gt;Now, let’s switch the &lt;code&gt;COUNT_BASED&lt;/code&gt; circuit breaker to &lt;code&gt;TIME_BASED&lt;/code&gt; circuit breaker. In &lt;code&gt;TIME_BASED&lt;/code&gt; circuit breaker, we will switch off our REST service after a second, and then we will click on here link from the home page. If 70 percent of calls in the last 10 seconds fail, our circuit breaker will open.&lt;/p&gt;

&lt;p&gt;Since REST Service is closed, we will see the following errors in &lt;code&gt;Circuitbreakdemo&lt;/code&gt; application&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl1wkjugmowxx170zvuc4.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl1wkjugmowxx170zvuc4.JPG" alt="Circuit Breaker in a Spring Boot Application - Errors"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We will see the number of errors before the circuit breaker will be in OPEN state.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhx7rz67zfn74yfn0bsym.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhx7rz67zfn74yfn0bsym.JPG" alt="Circuit Breaker in a Spring Boot Application - Open state"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;One configuration we can always add how long we want to keep the circuit breaker in the open state.  For the demo, I have added the circuit breaker will be in an open state for 10 seconds.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to handle OPEN circuit breakers?
&lt;/h2&gt;

&lt;p&gt;One question arises, how do you handle OPEN circuit breakers? Luckily, &lt;code&gt;resilience4j&lt;/code&gt; offers a fallback configuration with &lt;code&gt;Decorators&lt;/code&gt; utility. In most cases, you can always configure this to get the result from previous successful results so that users can still work with the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I have covered how to use a circuit breaker in a Spring Boot application. The code for this demo is available &lt;a href="https://github.com/yogsma/circuitbreakerdemo" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this demo, I have not covered how to monitor these circuit breaker events as &lt;code&gt;resilience4j&lt;/code&gt; the library allows storing these events with metrics that one can monitor with a monitoring system.&lt;/p&gt;

&lt;p&gt;If you enjoyed this post, consider subscribing to my blog &lt;a href="https://betterjavacode.com/subscribe" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>circuitbreaker</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>Simplifying Spring Security</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Fri, 19 Feb 2021 04:51:29 +0000</pubDate>
      <link>https://dev.to/betterjavacode/simplifying-spring-security-375a</link>
      <guid>https://dev.to/betterjavacode/simplifying-spring-security-375a</guid>
      <description>&lt;p&gt;Finally, the book is here. &lt;a href="https://gum.co/VgSdH"&gt;Simplifying Spring Security&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why I wrote this book?
&lt;/h2&gt;

&lt;p&gt;As part of writing this blog, I also follow few communities on Facebook. Most of these communities are related to Spring Framework and Spring Boot. The number of users asks questions related to Spring Security. Hence, I wondered why not write a book about it.&lt;/p&gt;

&lt;p&gt;Also as a developer, when I’m writing a Spring Boot application, I often use Spring Security. Accordingly, I always felt like I was using this mysterious library that solves my authentication problems.  I wanted to understand the fundamentals and how Spring Security dealt with authentication and authorization.&lt;/p&gt;

&lt;h2&gt;
  
  
  What do I cover?
&lt;/h2&gt;

&lt;p&gt;In the book, I cover from fundamentals of authentication, authorization, and how to use Spring Security for different authentication flows. Also, I show these flows with examples. As part of the book, you will also get access to a source code repository that you can play with.&lt;/p&gt;

&lt;p&gt;In short, I cover the following topics in the book:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Introduction

&lt;ol&gt;
&lt;li&gt;What is Spring Security?&lt;/li&gt;
&lt;li&gt;How Spring Security fits in with Spring Boot Application?&lt;/li&gt;
&lt;li&gt;Why you need Spring Security?&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Authentication

&lt;ol&gt;
&lt;li&gt;What is authentication?&lt;/li&gt;
&lt;li&gt;Authentication Architecture&lt;/li&gt;
&lt;li&gt;Types of Authentication&lt;/li&gt;
&lt;li&gt;Implementation of Different Flows&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Authorization

&lt;ol&gt;
&lt;li&gt;What is authorization?&lt;/li&gt;
&lt;li&gt;How does Spring Security handle authorization?&lt;/li&gt;
&lt;li&gt;What are GrantedAuthorities?&lt;/li&gt;
&lt;li&gt;Implementation of Authorization in an application&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Protection against common exploits

&lt;ol&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Transport Layer Security&lt;/li&gt;
&lt;li&gt;Security HTTP Response Headers&lt;/li&gt;
&lt;li&gt;Clickjacking Attack&lt;/li&gt;
&lt;li&gt;Cross-site Request Forgery Attack (CSRF)&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;Miscellaneous&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6A028DMQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2m7ix3i6of3u51vhzeqj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6A028DMQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2m7ix3i6of3u51vhzeqj.png" alt="Simplifying Spring Security" width="800" height="1277"&gt;&lt;/a&gt; &lt;br&gt;
&lt;a href="https://gum.co/VgSdH"&gt;Simplifying Spring Security&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why should you buy this book?
&lt;/h2&gt;

&lt;p&gt;First, it is a technical book and if you are a developer, it will easily help you improve your career. You’ll learn a lot about authentication and can solve some crucial security problems that many applications face.&lt;/p&gt;

&lt;p&gt;Most importantly, you can also build your own application and use any of these authentication mechanisms for the application.&lt;/p&gt;

&lt;p&gt;Subsequently, if you are getting started for a job in Spring Boot or Spring Framework, the book will also help you in preparing for Spring Security interviews.&lt;/p&gt;

</description>
      <category>spring</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>Step by Step Spring Batch Tutorial</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sun, 14 Feb 2021 20:22:02 +0000</pubDate>
      <link>https://dev.to/betterjavacode/step-by-step-spring-batch-tutorial-go7</link>
      <guid>https://dev.to/betterjavacode/step-by-step-spring-batch-tutorial-go7</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---jgu5ix7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/8qcxydymxbqmoipwl6n4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---jgu5ix7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/8qcxydymxbqmoipwl6n4.png" alt="Spring Batch Tutorial" width="600" height="600"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post, I want to show how you can use Spring Batch. This is a step by step Spring Batch Tutorial.&lt;/p&gt;

&lt;p&gt;In enterprise applications, batch processing is common. But with data becoming more prevalent on the internet, it has also become important how we process this data. There are multiple solutions available. &lt;a href="https://storm.apache.org/"&gt;Apache Storm&lt;/a&gt; or &lt;a href="https://spark.apache.org/"&gt;Apache Spark&lt;/a&gt; helps with processing and transforming the data in the required format. In this post, we will be looking at Spring Batch more closely.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Spring Batch?
&lt;/h2&gt;

&lt;p&gt;Spring Batch is a lightweight framework designed to facilitate batch processing. It allows developers to create batch applications. In turn, these batch applications process the incoming data and transform it for further usage.&lt;/p&gt;

&lt;p&gt;Another big advantage of using the &lt;a href="https://spring.io/projects/spring-batch"&gt;Spring Batch&lt;/a&gt; is that it allows for high-performance processing of this data. The applications that rely upon data heavily, it is of utmost importance that data becomes instantly available.&lt;/p&gt;

&lt;p&gt;Spring Batch allows a developer to use POJO based approach. In this approach, a developer can transform the batch-processed data into data models that she can further use for application business logic.&lt;/p&gt;

&lt;p&gt;In this post, I will cover an example where we will batch process a data-intensive CSV file for employee records and transform, validate that data to load into our database.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Batch Processing?
&lt;/h2&gt;

&lt;p&gt;Batch processing is a data processing mode. It involves consuming all the data, processing that data, transforming it, and then sending it to another data source. Usually, this is done through an automated job. Either a triggering system or a user triggers a job and that job processes the job definition. Job definition will be about consuming the data from its source.&lt;/p&gt;

&lt;p&gt;The key advantage of batch processing is it handles a large volume of data. Nevertheless, this operation can be asynchronous. Most applications perform batch processing separately from real-time user interaction.&lt;/p&gt;

&lt;p&gt;Next, we will learn about the Spring Batch framework and what it comprises.&lt;/p&gt;

&lt;h1&gt;
  
  
  Spring Batch Framework
&lt;/h1&gt;

&lt;p&gt;The following architecture shows the components of the Spring Batch framework.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--SMLVaG2X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/zhc86nhxkmg6idtvj8ok.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--SMLVaG2X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/zhc86nhxkmg6idtvj8ok.JPG" alt="Step by Step Spring Batch Tutorial" width="800" height="440"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First, the batch process involves a job. User schedules a job to be run at a certain time or based on a certain condition. This can also involve a job trigger.&lt;/p&gt;

&lt;p&gt;Spring Batch framework also includes&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;logging and tracing&lt;/li&gt;
&lt;li&gt;transaction management&lt;/li&gt;
&lt;li&gt;job processing statistics&lt;/li&gt;
&lt;li&gt;job restart&lt;/li&gt;
&lt;li&gt;resource management&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Usually, when you configure a job, it will be saved in the job repository. Job Repository keeps the metadata information of all the jobs. A trigger starts these jobs at their scheduled time.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;A job launcher&lt;/code&gt; is an interface to launch a job or runs a job when the jobs’ scheduled time arrives.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Job&lt;/code&gt; is defined with job parameters. When a job starts, a job instance runs for that job. Every execution of job instance has job execution and it keeps track status of the job. A job can have multiple steps.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Step&lt;/code&gt; is an independent phase of a job. A job can be comprised of more than one step. Similar to the job, each step has step execution that executes the step and keeps track of the status of the step.&lt;/p&gt;

&lt;p&gt;Each step has an &lt;code&gt;item reader&lt;/code&gt; that basically reads the input data, an &lt;code&gt;item processor&lt;/code&gt; that processes the data and transforms it, and an &lt;code&gt;item writer&lt;/code&gt; that takes the processed data and output it.&lt;/p&gt;

&lt;p&gt;Now, let’s see all these components in our demo.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step by Step Spring Batch Tutorial with an example
&lt;/h2&gt;

&lt;p&gt;As part of the demo, we will be uploading a csv file through Spring Batch Framework. So to start with, create the spring project and add the following dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;implementation 'org.springframework.boot:spring-boot-starter-batch'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the main dependency of our project. Also out main application will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.springbatchdemo;

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


@SpringBootApplication
public class SpringbatchdemoApplication
{

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

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Create DTO Object
&lt;/h3&gt;

&lt;p&gt;I will be uploading employee data through a CSV file, so I will have my DTO object for Employee created as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.springbatchdemo.dtos;

import com.betterjavacode.springbatchdemo.models.Company;
import com.betterjavacode.springbatchdemo.models.Employee;
import com.betterjavacode.springbatchdemo.repositories.CompanyRepository;
import org.springframework.beans.factory.annotation.Autowired;


import java.io.Serializable;

public class EmployeeDto implements Serializable
{
    private static final long serialVersionUID = 710566148641281929L;

    @Autowired
    public CompanyRepository companyRepository;

    private int employeeId;
    private int companyId;
    private String firstName;
    private String lastName;
    private String email;
    private String jobTitle;

    public EmployeeDto()
    {

    }

    public EmployeeDto(int employeeId, String firstName, String lastName, String email,
                        String jobTitle, int companyId)
    {
        this.employeeId = employeeId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.jobTitle = jobTitle;
        this.companyId = companyId;
    }

    public Employee employeeDtoToEmployee()
    {
        Employee employee = new Employee();
        employee.setEmployeeId(this.employeeId);
        employee.setFirstName(this.firstName);
        employee.setLastName(this.lastName);
        employee.setEmail(this.email);
        Company company = companyRepository.findById(this.companyId).get();
        employee.setCompany(company);
        employee.setJobTitle(this.jobTitle);
        return employee;
    }

    public int getEmployeeId ()
    {
        return employeeId;
    }

    public void setEmployeeId (int employeeId)
    {
        this.employeeId = employeeId;
    }

    public int getCompanyId ()
    {
        return companyId;
    }

    public void setCompanyId (int companyId)
    {
        this.companyId = companyId;
    }

    public String getFirstName ()
    {
        return firstName;
    }

    public void setFirstName (String firstName)
    {
        this.firstName = firstName;
    }

    public String getLastName ()
    {
        return lastName;
    }

    public void setLastName (String lastName)
    {
        this.lastName = lastName;
    }

    public String getEmail ()
    {
        return email;
    }

    public void setEmail (String email)
    {
        this.email = email;
    }

    public String getJobTitle ()
    {
        return jobTitle;
    }

    public void setJobTitle (String jobTitle)
    {
        this.jobTitle = jobTitle;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This DTO class also uses a repository &lt;code&gt;CompanyRepository&lt;/code&gt; to get a company object and convert DTO to a database object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting up Spring Batch Configuration
&lt;/h3&gt;

&lt;p&gt;Now, we will set up a batch configuration for our job that will run to upload a CSV file into the database. Our class &lt;code&gt;BatchConfig&lt;/code&gt; contain an annotation &lt;code&gt;@EnableBatchProcessing&lt;/code&gt;. This annotation enables Spring Batch features and provides a base configuration to set up batch jobs in a &lt;code&gt;@Configuration&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Configuration
@EnableBatchProcessing
public class BatchConfig
{

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This Batch Configuration will include a definition of our job, steps involved in the job. It will also include how we want to read our file data and process it further.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Bean
    public Job processJob(Step step)
    {
        return jobBuilderFactory.get("processJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener())
                .flow(step).end().build();
    }

    @Bean
    public Step orderStep1(JdbcBatchItemWriter writer)
    {
        return stepBuilderFactory.get("orderStep1").&amp;lt;EmployeeDto, EmployeeDto&amp;gt; chunk(10)
                .reader(flatFileItemReader())
                .processor(employeeItemProcessor())
                .writer(writer).build();
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above bean declares the job &lt;code&gt;processJob.incrementer&lt;/code&gt; adds job parameters. &lt;code&gt;listener&lt;/code&gt; will listen to job and handle job status. The bean for listener will handle job completion or job failure notification. As discussed in Spring Batch architecture, every job includes more than one step.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;@Bean&lt;/code&gt; for step uses &lt;code&gt;stepBuilderFactory&lt;/code&gt; to create a step. This step processes a chunk of data in a size of 10. It has a Flat File Reader &lt;code&gt;flatFileItemReader()&lt;/code&gt;. A processor &lt;code&gt;employeeItemReader&lt;/code&gt; will process the data that has been read by Flat File Item Reader.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Bean
    public FlatFileItemReader flatFileItemReader()
    {
        return new FlatFileItemReaderBuilder()
                .name("flatFileItemReader")
                .resource(new ClassPathResource("input/employeedata.csv"))
                .delimited()
                .names(format)
                .linesToSkip(1)
                .lineMapper(lineMapper())
                .fieldSetMapper(new BeanWrapperFieldSetMapper(){{
                    setTargetType(EmployeeDto.class);
                }})
                .build();
    }

    @Bean
    public LineMapper lineMapper()
    {
        final DefaultLineMapper defaultLineMapper = new DefaultLineMapper&amp;lt;&amp;gt;();
        final DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer();
        delimitedLineTokenizer.setDelimiter(",");
        delimitedLineTokenizer.setStrict(false);
        delimitedLineTokenizer.setNames(format);

        defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);
        defaultLineMapper.setFieldSetMapper(employeeDtoFieldSetMapper);

        return defaultLineMapper;
    }

    @Bean
    public EmployeeItemProcessor employeeItemProcessor()
    {
        return new EmployeeItemProcessor();
    }

    @Bean
    public JobExecutionListener listener()
    {
        return new JobCompletionListener();
    }

    @Bean
    public JdbcBatchItemWriter writer(final DataSource dataSource)
    {
        return new JdbcBatchItemWriterBuilder()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider&amp;lt;&amp;gt;())
                .sql("INSERT INTO employee(employeeId, firstName, lastName, jobTitle, email, " +
                        "companyId) VALUES(:employeeId, :firstName, :lastName, :jobTitle, :email," +
                        " " +
                        ":companyId)")
                .dataSource(dataSource)
                .build();
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will take a look at each of these beans now.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;FlatFileItemReader&lt;/code&gt; will read the data from the flat file. We are using a FlatFileItemReaderBuilder to create a FlatFileItemReader of type EmployeeDto.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;resource&lt;/code&gt; indicates the location of the file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;delimited&lt;/code&gt; – This builds a delimited tokenizer.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;names&lt;/code&gt; – will show the order of fields in the file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;lineMapper&lt;/code&gt; is an interface to map lines from file to domain object.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;fieldSetMapper&lt;/code&gt; will map the data from fieldset to an object.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;lineMapper&lt;/code&gt; bean needs tokenizer and fieldsetmapper.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;employeeDtoFieldSetMapper&lt;/code&gt; is another bean that we have autowired in this class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
package com.betterjavacode.springbatchdemo.configurations.processor;

import com.betterjavacode.springbatchdemo.dtos.EmployeeDto;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

@Component
public class EmployeeDtoFieldSetMapper implements FieldSetMapper
{

    @Override
    public EmployeeDto mapFieldSet (FieldSet fieldSet) throws BindException
    {
        int employeeId = fieldSet.readInt("employeeId");
        String firstName = fieldSet.readRawString("firstName");
        String lastName = fieldSet.readRawString("lastName");
        String jobTitle = fieldSet.readRawString("jobTitle");
        String email = fieldSet.readRawString("email");
        int companyId = fieldSet.readInt("companyId");

        return new EmployeeDto(employeeId, firstName, lastName, jobTitle, email, companyId);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, this FieldSetMapper maps fields to individual objects to create an &lt;code&gt;EmployeeDto&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;EmployeeItemProcessor&lt;/code&gt; implements the interface ItemProcessor. Basically in this class, we validate EmployeeDto data to verify if the company, the employee belongs to, exists.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;JobCompletionListener&lt;/code&gt; checks for job completion status.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Override
    public void afterJob(JobExecution jobExecution)
    {
        if (jobExecution.getStatus() == BatchStatus.COMPLETED)
        {
            // Log statement
            System.out.println("BATCH JOB COMPLETED SUCCESSFULLY");
        }
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let’s look at &lt;code&gt;ItemWriter&lt;/code&gt;. This bean basically uses &lt;code&gt;JdbcBatchItemWriter&lt;/code&gt;. &lt;code&gt;JdbcBatchItemWriter&lt;/code&gt; uses INSERT sql statement to insert processed EmployeeDto data into the configured data source.&lt;/p&gt;

&lt;h3&gt;
  
  
  Configuring Application Properties
&lt;/h3&gt;

&lt;p&gt;Before we run our application to process a file, let’s look at &lt;code&gt;application.properties&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
spring.datasource.url=jdbc:mysql://127.0.0.1/springbatchdemo?autoReconnect=true&amp;amp;useSSL=false
spring.datasource.username = root
spring.datasource.password=*******
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.datasource.hikari.connection-test-query=SELECT 1
spring.batch.initialize-schema=ALWAYS

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other than regular data source properties, we should understand the property &lt;code&gt;spring.batch.initialize-schema=ALWAYS&lt;/code&gt;.  If we don’t use this property and start the application, the application will complain &lt;code&gt;Table batch_job_instance doesn't exist&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To avoid this error, we are basically telling to create batch job-related metadata during startup. This property will create additional database tables in your database like &lt;code&gt;batch_job_execution&lt;/code&gt;, &lt;code&gt;batch_job_execution_context&lt;/code&gt;, &lt;code&gt;batch_job_execution_params&lt;/code&gt;, &lt;code&gt;batch_job_instance&lt;/code&gt; etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demo
&lt;/h2&gt;

&lt;p&gt;Now if I execute my Spring Boot Application, it will run and execute the job. There are different ways to trigger a job. In an enterprise application, you will receive a file or data in some kind of storage place (S3 or Amazon SNS-SQS), you will have a job that will be monitoring this location to trigger file loading Spring Batch job.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i8nYlcus--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/06dqu5dynnepxmdil63e.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i8nYlcus--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/06dqu5dynnepxmdil63e.JPG" alt="Step by Step Spring Batch Tutorial Job Completion" width="800" height="162"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can see in the execution a message about job completion – &lt;strong&gt;“BATCH JOB COMPLETED SUCCESSFULLY“&lt;/strong&gt;. If we check our database table, we will see the data loaded.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lDQ6yKt0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/nhnwfjh5bnq6zuve4a9t.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lDQ6yKt0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/i/nhnwfjh5bnq6zuve4a9t.JPG" alt="Step by Step Spring Batch Tutorial Employee Data" width="800" height="678"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can download code for this demo from my &lt;a href="https://github.com/yogsma/springbatchdemo"&gt;github repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What more?
&lt;/h2&gt;

&lt;p&gt;I have covered a Spring Batch tutorial here, but this is not all. There is more to Spring Batch than this introductory part. You can have different input data sources or you can also load the data from file to file with various data processing rules.&lt;/p&gt;

&lt;p&gt;There are also ways to automate these jobs and process a high volume of data in a performant manner.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I showed a step by step Spring Batch Tutorial. There are many ways to handle batch jobs, but Spring Batch has made this very easy.&lt;/p&gt;

&lt;p&gt;In other news, I recently released my new book – Simplifying Spring Security. If you are looking to learn about Spring Security, you can buy the book &lt;a href="https://gumroad.com/l/VgSdH"&gt;here&lt;/a&gt;. Accompany this book with this post of  &lt;a href="https://betterjavacode.com/spring-boot/top-21-spring-boot-interview-questions"&gt;Spring Boot Interview questions&lt;/a&gt; and you will be ready for your next job interview.&lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>batchprocessing</category>
    </item>
    <item>
      <title>Spring Boot CRUD Application Example with MongoDB</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sat, 23 Jan 2021 17:14:00 +0000</pubDate>
      <link>https://dev.to/betterjavacode/spring-boot-crud-application-example-with-mongodb-5dl1</link>
      <guid>https://dev.to/betterjavacode/spring-boot-crud-application-example-with-mongodb-5dl1</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this post, I will show how we can use Spring Boot to build a simple CRUD REST application example with MongoDB. I know your first question will be what is MongoDB?&lt;/p&gt;

&lt;h2&gt;
  
  
  What is MongoDB?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://betterjavacode.com/programming/fundamentals-of-a-distributed-system-design" rel="noopener noreferrer"&gt;MongoDB&lt;/a&gt; is a NoSQL document database. In this database, records are documents that behave a lot like JSON objects. So it is mostly key-value pair.&lt;/p&gt;

&lt;p&gt;The key advantages of using MongoDB as a database are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MongoDB is a schema less document database. One collection holds different documents.&lt;/li&gt;
&lt;li&gt;Structure of a single object is clear.&lt;/li&gt;
&lt;li&gt;No complex joins.&lt;/li&gt;
&lt;li&gt;Deep query ability.&lt;/li&gt;
&lt;li&gt;Easy to scale-out&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are a few reasons why you would use MongoDB or similar NoSQL databases in enterprise applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If you need faster data retrieval in JSON style&lt;/li&gt;
&lt;li&gt;Easy to add index on an attribute&lt;/li&gt;
&lt;li&gt;For Sharding purposes – Sharding is the process of storing data records across multiple machines. You will usually partition this data according to some criteria while storing across multiple machines.&lt;/li&gt;
&lt;li&gt;Fast in-place updates&lt;/li&gt;
&lt;li&gt;Easier to query&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;To create this sample application, you need:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring Boot (version 2.4.1)&lt;/li&gt;
&lt;li&gt;MongoDB&lt;/li&gt;
&lt;li&gt;Gradle&lt;/li&gt;
&lt;li&gt;Java&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Spring Boot CRUD Application
&lt;/h2&gt;

&lt;p&gt;As part of this post, I will be building a REST CRUD application. &lt;/p&gt;

&lt;p&gt;This includes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A book library – We will be creating a collection library in our MongoDB database.&lt;/li&gt;
&lt;li&gt;A library where we will be storing the books by author&lt;/li&gt;
&lt;li&gt;A user can call the REST API to retrieve the book by author&lt;/li&gt;
&lt;li&gt;A user can call the REST API to retrieve all the books from the library&lt;/li&gt;
&lt;li&gt;POST – /v1/mongodbapp/books – To add a book to library&lt;/li&gt;
&lt;li&gt;GET – /v1/mongodbapp/books – To retrieve all the books from the 
library&lt;/li&gt;
&lt;li&gt;GET – /v1/mongodbapp/books/id – To retrieve a specific book&lt;/li&gt;
&lt;li&gt;DELETE – /v1/mongodbapp/books/id – To remove a book from the library&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to use Spring Boot CRUD with MongoDB
&lt;/h2&gt;

&lt;p&gt;To get started with creating this application, we will be using gradle to handle our dependencies and build the application. Add the following dependencies in our Spring Boot application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-web'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once we have these dependencies, we will be able to connect to mongo db database. But we still need to add where our database is located. We will add the required properties in our &lt;code&gt;application.properties&lt;/code&gt; file as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.data.mongodb.host = localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=library

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will allow us to connect to MongoDB database running at host localhost on the port &lt;code&gt;27017&lt;/code&gt; and the database schema is library.&lt;/p&gt;

&lt;h3&gt;
  
  
  Define Data Model
&lt;/h3&gt;

&lt;p&gt;As part of the library, we will need books. So our main data object is Book. The data model for this will include the book title, author, and ISBN. This will be as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.mongodbdemo.mongodbapp.models;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;



@Document(collection = "books")
public class Book
{
    @Id
    private String id;

    private String title;
    private String author;
    private String isbn;

    public Book()
    {

    }

    public Book(String title, String author, String isbn)
    {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

    public String getId ()
    {
        return id;
    }

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

    public String getTitle ()
    {
        return title;
    }

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

    public String getAuthor ()
    {
        return author;
    }

    public void setAuthor (String author)
    {
        this.author = author;
    }

    public String getIsbn ()
    {
        return isbn;
    }

    public void setIsbn (String isbn)
    {
        this.isbn = isbn;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are using MongoDB, &lt;code&gt;@Document&lt;/code&gt; annotation overrides the collection books.&lt;/p&gt;

&lt;h3&gt;
  
  
  Add Repository Interface
&lt;/h3&gt;

&lt;p&gt;We will need a repository interface to fetch, save or delete our book object.  In &lt;code&gt;repositories&lt;/code&gt; package, we will add &lt;code&gt;BookRepository&lt;/code&gt; interface&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.mongodbdemo.mongodbapp.repositories;

import com.betterjavacode.mongodbdemo.mongodbapp.models.Book;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface BookRepository extends MongoRepository&amp;lt;Book, String&amp;gt;
{
    List findByTitleContaining(String title);
    List findByAuthor(String name);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This repository has two methods to fetch list of books by a title or by author name.&lt;/p&gt;

&lt;h3&gt;
  
  
  Add Spring REST API Controller
&lt;/h3&gt;

&lt;p&gt;Now to make our application REST CRUD, we will add a REST controller. This controller will contain &lt;code&gt;POST&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, &lt;code&gt;GET&lt;/code&gt; and &lt;code&gt;DELETE&lt;/code&gt; APIs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.mongodbdemo.mongodbapp.controller;

import com.betterjavacode.mongodbdemo.mongodbapp.models.Book;
import com.betterjavacode.mongodbdemo.mongodbapp.repositories.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@CrossOrigin("http://localhost:8080")
@RestController
@RequestMapping("/v1/mongodbapp")
public class BookController
{
    @Autowired
    BookRepository bookRepository;

    @GetMapping("/books")
    public ResponseEntity&amp;lt;List&amp;gt; getAllBooks(@RequestParam(required = false) String bookTitle)
    {
        try
        {
            List listOfBooks = new ArrayList&amp;lt;&amp;gt;();
            if(bookTitle == null || bookTitle.isEmpty())
            {
                bookRepository.findAll().forEach(listOfBooks::add);
            }
            else
            {
                bookRepository.findByTitleContaining(bookTitle).forEach(listOfBooks::add);
            }

            if(listOfBooks.isEmpty())
            {
                return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NO_CONTENT);
            }

            return new ResponseEntity&amp;lt;&amp;gt;(listOfBooks, HttpStatus.OK);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/books/{id}")
    public ResponseEntity getBookById(@PathVariable("id") String id)
    {
        try
        {
            Optional bookOptional = bookRepository.findById(id);

            return new ResponseEntity&amp;lt;&amp;gt;(bookOptional.get(), HttpStatus.OK);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/books")
    public ResponseEntity addABookToLibrary(@RequestBody Book book)
    {
        try
        {
            Book createdBook = bookRepository.save(new Book(book.getTitle(), book.getAuthor(),
                    book.getIsbn()));
            return new ResponseEntity&amp;lt;&amp;gt;(createdBook, HttpStatus.CREATED);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/books/{id}")
    public ResponseEntity updateABook(@PathVariable("id") String id, @RequestBody Book book)
    {
        Optional bookOptional = bookRepository.findById(id);

        if(bookOptional.isPresent())
        {
            Book updatedBook = bookOptional.get();
            updatedBook.setTitle(book.getTitle());
            updatedBook.setAuthor(book.getAuthor());
            updatedBook.setIsbn(book.getIsbn());
            return new ResponseEntity&amp;lt;&amp;gt;(bookRepository.save(updatedBook), HttpStatus.OK);
        }
        else
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NOT_FOUND);
        }
    }

    @DeleteMapping("/books/{id}")
    public ResponseEntity deleteABook(@PathVariable("id") String id)
    {
        try
        {
            bookRepository.deleteById(id);
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NO_CONTENT);
        }
        catch (Exception e)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;BookController&lt;/code&gt; is our REST Controller class. It includes&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;* @RestController – to mark this as a REST controller.

&lt;ul&gt;
&lt;li&gt;@CrossOrigin – This annotation allows cross-origin resource sharing (CORS). This will add CORS access control headers in the REST response. These headers are necessary because it allows servers to specify not only who can access the resources, but how they can be accessed.&lt;/li&gt;
&lt;li&gt;We have added different methods – addABookToLibrary adds the book to database, getAllBooks retrieves the book from database.
&lt;/li&gt;
&lt;/ul&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;


The Complete Demo
&lt;/h2&gt;


&lt;p&gt;Now we have added our REST controller, repository methods, we will build and run this application. As part of the demo, I will use POSTMAN to access APIs.&lt;/p&gt;

&lt;p&gt;You can build the application from command line or from the code editor you are using. I prefer command line, so I already built the application. Once built, you can run the program as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;java -jar mongodbapp-0.0.1-SNAPSHOT.jar.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let’s use POSTMAN to add books to our library.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fxaqlo443iw6saxql2za9.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fxaqlo443iw6saxql2za9.JPG" alt="Spring Boot CRUD Application MongoDB - Create"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As shown above, we added a book and the response shows the added book in the database.&lt;/p&gt;

&lt;p&gt;The following API is a GET API to get all the books from the database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdmwiqh6oocu7qlqwqegx.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fdmwiqh6oocu7qlqwqegx.JPG" alt="Spring Boot CRUD Application MongoDB - Get All"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now to show delete the book from library, we will use DELETE API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fonbivgvo9778inz8gyx7.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fonbivgvo9778inz8gyx7.JPG" alt="Spring Boot CRUD Application MongoDB - Delete"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The code for this sample application is available in my &lt;a href="https://github.com/yogsma/mongodbapp" rel="noopener noreferrer"&gt;github repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you want to see this data in MongoDB database, you can access MongoDB compass tool and access the collection books in library database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fem8gzv2vzujzcfhkfbbn.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fem8gzv2vzujzcfhkfbbn.JPG" alt="Mongo DB"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I showed how to use Spring Boot to create REST API while using MongoDB database. The approach we used is very similar to what we have while using a regular SQL database. There are some changes that we have to add while using NoSQL database. If you find this post useful or have any questions that I can help you with, you can subscribe to my blog &lt;a href="https://betterjavacode.com/subscribe" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>spring</category>
      <category>java</category>
      <category>mongodb</category>
      <category>gradle</category>
    </item>
    <item>
      <title>Top 21 Spring Boot Interview Questions</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sun, 10 Jan 2021 17:03:40 +0000</pubDate>
      <link>https://dev.to/betterjavacode/top-21-spring-boot-interview-questions-1705</link>
      <guid>https://dev.to/betterjavacode/top-21-spring-boot-interview-questions-1705</guid>
      <description>&lt;p&gt;In the last few months, I have received a few requests about Spring Boot Interview Questions. In this post, I will cover the top 21 Spring Boot Interview Questions. Additionally, I will also cover some Microservice architecture related questions.&lt;/p&gt;

&lt;p&gt;I have divided these Spring Boot interview questions into three categories – for a novice, for intermediate, and for an experienced developer. So if you don’t have any experience with Spring Boot, novice questions will help you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Boot Interview Questions for Novice Developers
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What is Spring Boot and How is it useful in Web Application Development?
&lt;/h3&gt;

&lt;p&gt;Spring Boot is a framework built on top of Spring Framework for rapid application development. Similarly, Ruby on Rails, Django with Python web frameworks are famous. Particularly, Spring brought a much-needed web framework to Java to build web applications. Important features like embedded application server and auto-configuration allow rapid development and deployment.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Spring Boot framework allows importing dependencies easily.&lt;/li&gt;
&lt;li&gt;It also eases in using Spring Security in the applications with its rich features.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://betterjavacode.com/java/spring-boot-actuator"&gt;Actuator&lt;/a&gt; – One can implement production-ready features for monitoring the application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. What are the differences between Spring Boot and Spring?
&lt;/h3&gt;

&lt;p&gt;Spring framework includes multiple features that can be used in the Spring Boot framework. On the other hand, the Spring Boot framework is used for application development.&lt;/p&gt;

&lt;p&gt;Equally, Spring framework provides features like data binding, dependency injection, aspect-oriented programming, data access, security.&lt;/p&gt;

&lt;p&gt;In short, Spring Boot is one of the modules of Spring Framework. Spring Boot is built on the top of the Spring framework. Spring Boot is a microservice-based framework to build applications. The feature of auto-configuration in Spring Boot helps in reducing lines of code.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. How can you set up the Spring Boot application with maven or gradle?
&lt;/h3&gt;

&lt;p&gt;To set up a spring boot application, one can use maven or gradle. Both are used to pull required dependencies in the application. Particularly, for spring boot application, one can pull &lt;code&gt;spring-boot-starter-parent&lt;/code&gt; dependency.&lt;/p&gt;

&lt;p&gt;In maven, one uses &lt;code&gt;pom.xml&lt;/code&gt; file and in gradle, one uses &lt;code&gt;build.gradle&lt;/code&gt; for dependencies declaration&lt;/p&gt;

&lt;p&gt;Maven:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;2.4.1&amp;lt;/version&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Gradle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;compile group: 'org.springframework.boot', name: 'spring-boot', version: '2.4.1'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. How can you change the default port of Spring Boot Application?
&lt;/h3&gt;

&lt;p&gt;There are three ways you can change the default port of the Spring Boot Application. Consequently, the most straight forward way is to use &lt;code&gt;application.properties&lt;/code&gt; or &lt;code&gt;application.yml&lt;/code&gt; file.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;server.port&lt;/code&gt; use this property in application.properties.&lt;/li&gt;
&lt;li&gt;You can also change the port programmatically in the main &lt;code&gt;@SpringBootApplication&lt;/code&gt; class.&lt;/li&gt;
&lt;li&gt;You can use the port of your choice while starting the application as a jar file. &lt;code&gt;java -jar -Dserver.port=8980 myapplication.jar&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. How would you set up an application with HTTPS port with Spring Boot?
&lt;/h3&gt;

&lt;p&gt;By default, the Spring Boot application runs on HTTP port. To make your application run with HTTPS port, there are two ways.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One can use &lt;code&gt;server.port&lt;/code&gt;, &lt;code&gt;server.ssl.key-store-password&lt;/code&gt;,&lt;code&gt;server.ssl.key-store&lt;/code&gt; ,&lt;code&gt;server.ssl.key-store-type&lt;/code&gt; and &lt;code&gt;server.ssl.key-alias&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Another way to use the HTTPS port is programmatically.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  6. What embedded servers does Spring Boot support?
&lt;/h3&gt;

&lt;p&gt;Spring Boot application supports Tomcat, Jetty, and Undertow webservers. By default, the Tomcat web server is supported by Spring Boot’s web starter.&lt;/p&gt;

&lt;p&gt;To change the default web server, one has to exclude &lt;code&gt;spring-boot-starter-tomcat&lt;/code&gt; and include corresponding server starter like jetty or undertow.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;exclusions&amp;gt;
        &amp;lt;exclusion&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-tomcat&amp;lt;/artifactId&amp;gt;
        &amp;lt;/exclusion&amp;gt;
    &amp;lt;/exclusions&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-jetty&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. What are the advantages of Spring Boot?
&lt;/h3&gt;

&lt;p&gt;Here are the main advantages of Spring Boot&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Allows to create stand-alone Spring applications&lt;/li&gt;
&lt;li&gt;One can easily use tomcat, jetty, or undertow server&lt;/li&gt;
&lt;li&gt;Rapid Development&lt;/li&gt;
&lt;li&gt;Also allows using Microservice-based architecture easily&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Spring Boot Interview Questions for Intermediate Developers
&lt;/h2&gt;

&lt;p&gt;So far, I have covered some basic interview questions. If you are a developer with a few years of experience in Java or Spring Boot Development, the next set of questions will help you where to improve on.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. How to deploy Spring Boot Web Application as a jar and war files?
&lt;/h3&gt;

&lt;p&gt;Generally, we deploy web application as web archive file (WAR). We deploy the war file on the external web server.&lt;/p&gt;

&lt;p&gt;Evidently, Spring offers a plugin &lt;code&gt;spring-boot-maven-plugin&lt;/code&gt; if using maven to build the application. You can then pack the web application as an executable jar file. If using gradle, gradle build will create an executable jar file by default.&lt;/p&gt;

&lt;p&gt;For maven,&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;packaging&amp;gt;jar&amp;lt;/packaging&amp;gt;&lt;/code&gt; will build a jar file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;packaging&amp;gt;war&amp;lt;/packaging&amp;gt;&lt;/code&gt; will build a war file. If the packaging element is not included, the maven will jar file by default. You also need to keep the container dependency as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-tomcat&amp;lt;/artifactId&amp;gt;
    &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For gradle, you need to mark the embedded container’s dependencies as belonging to the war plugin’s &lt;code&gt;providedRuntime&lt;/code&gt; configuration.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. Why do we use the annotation &lt;code&gt;@SpringBootApplication&lt;/code&gt; in the main Spring Boot application class?
&lt;/h3&gt;

&lt;p&gt;For applications to use auto-configuration, component scans, and extra configurations, one can include one single annotation &lt;code&gt;@SpringBootApplication&lt;/code&gt;. This annotation includes three annotations &lt;code&gt;@EnableAutoConfiguration&lt;/code&gt;, &lt;code&gt;@ComponentScan&lt;/code&gt;, and &lt;code&gt;@Configuration&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@EnableAutoConfiguration&lt;/code&gt; – enable Spring Boot’s auto-configuration&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@ComponentScan&lt;/code&gt; – this allows scanning the packages where the application is located.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@Configuration&lt;/code&gt; – allow registering extra beans in the context or import additional configuration classes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  10. What are &lt;code&gt;@RestController&lt;/code&gt; and &lt;code&gt;@RequestMapping&lt;/code&gt; annotation used for?
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;@RestController&lt;/code&gt; – This annotation adds annotations @Controller and @ResponseBody. This annotation marks a class that will handle the incoming requests. Usually, this annotation is used to create RESTful APIs.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;@RequestMapping&lt;/code&gt; – This annotation provides routing information in the class that handles incoming requests. This annotation maps the incoming HTTP requests to the corresponding method.&lt;/p&gt;

&lt;h3&gt;
  
  
  11. Why do we need Spring Profiles?
&lt;/h3&gt;

&lt;p&gt;When building enterprise applications, we use different environments like Dev, Test, QA, and Production. Spring Boot allows configuring application properties differently for each of these environments.&lt;/p&gt;

&lt;p&gt;To help separate the configuration for each environment, one can name the properties file according to the environment like &lt;code&gt;application-dev.properties&lt;/code&gt;, &lt;code&gt;application-test.properties&lt;/code&gt;, and &lt;code&gt;application-prod.properties&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  12. How to disable specific auto-configuration?
&lt;/h3&gt;

&lt;p&gt;To disable any specific auto-configuration, one can use &lt;code&gt;exclude&lt;/code&gt; attribute for &lt;code&gt;@EnableAutoConfiguration&lt;/code&gt; annotation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class SampleApplication
{
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  13. What is Thymeleaf and how to use it?
&lt;/h3&gt;

&lt;p&gt;Thymeleaf is a server-side template engine for a web application. Its main purpose is to bring natural templates to the web application.&lt;/p&gt;

&lt;p&gt;Specifically, one has to include the dependency &lt;code&gt;spring-boot-starter-thymeleaf&lt;/code&gt; in the application to use thymeleaf.&lt;/p&gt;

&lt;h3&gt;
  
  
  14. What are the different Spring Boot starters out there and what purpose you can use them?
&lt;/h3&gt;

&lt;p&gt;Emphatically, one major advantage of Spring Boot is to be able to use various dependencies for your Spring Boot application. All starter Spring Boot dependencies are under the &lt;code&gt;org.springframework.boot&lt;/code&gt; group. These dependencies start with &lt;code&gt;spring-boot-starter-&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are more than 50 starter dependencies, but here is a list of dependencies that most developers will use in their applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter&lt;/code&gt; – Core starter. This includes auto-configuration, logging, and YAML.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-data-jpa&lt;/code&gt; – This includes Spring data JPA with hibernate.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-security&lt;/code&gt; – Spring Security model offers security for your web application. By default, it will add basic form-based authentication.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-web&lt;/code&gt; – This includes a web module and helps to create web, RESTful applications using Spring MVC.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-thymeleaf&lt;/code&gt; – Importing this module allows the developer to use thymeleaf template engine in the application.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-jdbc&lt;/code&gt; – This module helps in connecting to the database for your application.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;spring-boot-starter-tomcat&lt;/code&gt; – Usually, this is part of the spring boot parent module. This allows a developer to use an embedded tomcat servlet container.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Spring Boot Interview Questions for Experienced Developers
&lt;/h2&gt;

&lt;p&gt;The next set of questions are for an experienced developer. Despite the distinction, a beginner as well as an intermediate developer should learn about these questions.&lt;/p&gt;

&lt;h3&gt;
  
  
  15. How do you connect Spring Boot Application to the database using JPA?
&lt;/h3&gt;

&lt;p&gt;Spring Boot provides &lt;code&gt;spring-boot-starter-data-jpa&lt;/code&gt; dependency to connect Spring application to a relational database.&lt;/p&gt;

&lt;p&gt;On the other hand, Spring Data JPA handles the complexity of JDBC-based database access and object-relational modeling. Consequently, it improves the implementation of data access layer handling. From the developer’s point of view, it reduces the dependency on relational database querying.&lt;/p&gt;

&lt;p&gt;JPA allows mapping application classes to database tables.&lt;/p&gt;

&lt;h3&gt;
  
  
  16. Why do you use the Spring Boot Actuator?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html"&gt;Spring Boot Actuator&lt;/a&gt; brings production-ready features to the application. As a result, one can easily monitor the application.&lt;/p&gt;

&lt;p&gt;It also provides auditing, health check, and different metrics for the application. Therefore, you include dependency as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-actuator&amp;lt;/artifactId&amp;gt;
    &amp;lt;scope&amp;gt;provided&amp;lt;/scope&amp;gt;
&amp;lt;/dependency&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are some of the endpoints that this dependency provides for the application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;env – Endpoint to display all the environment properties&lt;/li&gt;
&lt;li&gt;health – Endpoint to show application’s health&lt;/li&gt;
&lt;li&gt;metrics – This Endpoint displays various metrics of the application&lt;/li&gt;
&lt;li&gt;loggers – Display the configuration of loggers in the application&lt;/li&gt;
&lt;li&gt;httptrace – Endpoint to show HTTP trace information&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  17. What is Spring Boot Devtools used for?
&lt;/h3&gt;

&lt;p&gt;Spring Boot DevTools or Developer Tools are a set of tools that make the development process easier. To include DevTools support, one has to add the dependency &lt;code&gt;spring-boot-devtools&lt;/code&gt; in the project.&lt;/p&gt;

&lt;p&gt;Spring Boot DevTools helps in disabling the caching that many spring boot dependencies use. This is useful in the development process as the developer wants to see the changes immediately.&lt;/p&gt;

&lt;p&gt;Additionally, using this library allows applications to restart whenever there is a change in files on the classpath.&lt;/p&gt;

&lt;p&gt;Moreover, the library enables debug logging for the web group.&lt;/p&gt;

&lt;h3&gt;
  
  
  18. What is the advantage of using Spring Data JPA?
&lt;/h3&gt;

&lt;p&gt;Spring Data Jpa provides JpaTemplate to integrate Spring application with JPA. You can also choose a specific implementation of JPA specification. By default, it will be Hibernate.&lt;/p&gt;

&lt;p&gt;Advantages of Spring Data JPA&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduces boilerplate code&lt;/li&gt;
&lt;li&gt;Generated Queries help in reducing developer’s dependency on database queries&lt;/li&gt;
&lt;li&gt;Repository pattern allows developers to handle persistence easily.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  19. Explain Spring Boot supports relaxed binding.
&lt;/h3&gt;

&lt;p&gt;Generally, the key of a property needs to be an exact match of a property name in the Spring Boot application. Spring Boot supports relaxed binding which means the key of a property doesn’t have to be an exact match of a property name.&lt;/p&gt;

&lt;p&gt;Moreover, the environment property can be written in any case. Example – If you have a property &lt;code&gt;propertyDB&lt;/code&gt; in your bean class with annotation &lt;code&gt;@ConfigurationProperties&lt;/code&gt;, you can bind that property to any of these environment properties – &lt;code&gt;PROPERTYDB&lt;/code&gt;, &lt;code&gt;propertydb&lt;/code&gt;, or &lt;code&gt;property_db&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  20. If you want to use Spring Security in your application, how do you use it, and how it makes the application secure?
&lt;/h3&gt;

&lt;p&gt;Presently, to secure your Spring Boot application, you can include &lt;code&gt;spring-boot-starter-security&lt;/code&gt; dependency in your project. By default, it will add some of the security measures for your application. These default measures include adding basic form-based authentication to your application or securing REST APIs.&lt;/p&gt;

&lt;p&gt;Subsequently, to leverage the Spring Security, one can extend &lt;code&gt;WebSecurityConfigurerAdapter&lt;/code&gt; class to add custom security measures. In the same class, you will use &lt;code&gt;@EnableWebSecurity&lt;/code&gt; annotation. This annotation allows Spring to find configurations and apply the class to global WebSecurity.&lt;/p&gt;

&lt;h3&gt;
  
  
  21. What do you use the annotation &lt;code&gt;@ControllerAdvice&lt;/code&gt; for?
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;@ControllerAdvice&lt;/code&gt; annotation helps in managing the exceptions in Spring Boot Application. In short, it is an interceptor of exceptions thrown by methods annotated with @RequestMapping.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ResponseEntityExceptionHandler&lt;/code&gt; is the base class that provides centralized exception handling.&lt;/p&gt;

&lt;p&gt;So far, I have covered Spring Boot interview questions. I will still cover a few Microservices interview questions that can help developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Microservices Interview Questions
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. What is Microservices?
&lt;/h3&gt;

&lt;p&gt;Microservices is an architectural style. It structures an application as a collection of services that are&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Highly maintainable&lt;/li&gt;
&lt;li&gt;Loosely coupled&lt;/li&gt;
&lt;li&gt;Easily deployable&lt;/li&gt;
&lt;li&gt;Owned by a small team&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. What are the common tools used to build and deploy microservices?
&lt;/h3&gt;

&lt;p&gt;This depends on the technology stack. &lt;code&gt;Docker&lt;/code&gt; remains one common tool irrespective of the technology stack. Hence, docker allows creating a container for the microservice. This container then can be deployed in the cloud environment.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Wiremock&lt;/code&gt; is another tool for flexible API mocking for microservices.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Hysterix&lt;/code&gt; is a circuit breaker that helps in latency and fault-tolerance of the application.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. How does Spring help in Microservices development?
&lt;/h3&gt;

&lt;p&gt;Most importantly, Spring helps in rapid development. Spring Boot helps in building REST APIs, web applications. Spring Cloud helps in integrating with external systems.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. What are the challenges with Microservices?
&lt;/h3&gt;

&lt;p&gt;Microservices rely on each other. Consequently, communication between these services needs to be secured. Since microservices are a distributed system, it can become a complex model. There can be an operational overhead. More services mean more resources.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I covered the most questions on Spring Boot that you might face during an interview. I hope you find this post helpful.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>microservices</category>
      <category>java</category>
      <category>spring</category>
    </item>
    <item>
      <title>Spring WebClient vs RestTemplate – Comparison and Features</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sun, 27 Dec 2020 18:30:38 +0000</pubDate>
      <link>https://dev.to/betterjavacode/spring-webclient-vs-resttemplate-comparison-and-features-3cgp</link>
      <guid>https://dev.to/betterjavacode/spring-webclient-vs-resttemplate-comparison-and-features-3cgp</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Spring 5 introduced a new reactive web client called WebClient. In this post, I will show when and how we can use Spring WebClient vs RestTemplate. I will also describe what features WebClient offers.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is RestTemplate?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://betterjavacode.com/java/consuming-a-restful-webservice-part-iv"&gt;RestTemplate&lt;/a&gt; is a central Spring class that allows HTTP access from the client-side. RestTemplate offers POST, GET, PUT, DELETE, HEAD, and OPTIONS HTTP methods. The simple use case of RestTemplate is to consume Restful web services.&lt;/p&gt;

&lt;p&gt;You can create a bean that provides the instance of RestTemplate. You can then &lt;code&gt;@autowire&lt;/code&gt; this bean in any class where you plan to call REST services. RestTemplate is the class that implements the interface &lt;code&gt;RestOperations&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The following code shows the declaration of the bean:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Bean
    public RestOperations restOperations()
    {
        return new RestTemplate();
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following code shows a REST client &lt;code&gt;YelpClient&lt;/code&gt; calling Yelp’s REST API to get rental property reviews.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   @Autowired
   private final RestOperations restOperations;

   public List getRentalPropertyReviews(String address)
   {
        String url = buildRestUrl(businessId);
        HttpHeaders httpHeaders = new HttpHeaders();
        String apiKey = getApiKey(YELP);
        httpHeaders.add("Authorization","Bearer " + apiKey);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity entity = new HttpEntity("parameters", httpHeaders);
        ResponseEntity response;

        try
        {
            response = restOperations.exchange(url, HttpMethod.GET,entity, String.class);
        }
        catch(RestClientException e)
        {
            throw new RuntimeException("Unable to retrieve reviews", e);
        }

    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we are building HTTP Headers by adding Yelp’s REST API key as part of the authorization. We call the GET method to get review data.&lt;/p&gt;

&lt;p&gt;Basically, one has to do&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Autowire the RestTemplate object&lt;/li&gt;
&lt;li&gt;Build HTTP Headers with authorization and Content Type&lt;/li&gt;
&lt;li&gt;Use HttpEntity to wrap the request object&lt;/li&gt;
&lt;li&gt;Provide URL, Http Method, and the Return type for exchange method.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is WebClient?
&lt;/h2&gt;

&lt;p&gt;Spring 5 introduced a reactive web client called WebClient. It’s an interface to perform web requests. It is part of the Spring web reactive module. WebClient will be replacing RestTemplate eventually.&lt;/p&gt;

&lt;p&gt;Most importantly, WebClient is reactive, nonblocking, asynchronous, and works over HTTP protocol Http/1.1.&lt;/p&gt;

&lt;p&gt;To use WebClient, one has to do&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create an instance of WebClient&lt;/li&gt;
&lt;li&gt;Make a request to the REST endpoint&lt;/li&gt;
&lt;li&gt;Handle the response
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WebClient webClient = WebClient
       .builder()
       .baseUrl("https://localhost:8443")
       .defaultCookie("cookieKey", "cookieValue")
       .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) 
       .defaultUriVariables(Collections.singletonMap("url", "https://localhost:8443"))
       .build();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code shows one way to instantiate WebClient. You can also create an instance by simply using &lt;code&gt;WebClient webClient = WebClient.create();&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;WebClient provides two methods &lt;code&gt;exchange&lt;/code&gt; and &lt;code&gt;retrieve&lt;/code&gt;. exchange method usually fetches the response along with status and headers. retrieve method gets the response body directly. It’s easier to use.&lt;/p&gt;

&lt;p&gt;Also depending on if you are trying to fetch a single object in response or a list of objects, you can use &lt;code&gt;mono&lt;/code&gt; or &lt;code&gt;flux&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;this.webClient =
                webClientBuilder.baseUrl("http://localhost:8080/v1/betterjavacode/").build();

this.webClient.get()
                .uri("users")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve().bodyToFlux(UserDto.class).collectList();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code basically uses &lt;code&gt;webClient&lt;/code&gt; to fetch a list of users from the REST API.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring WebClient vs RestTemplate
&lt;/h2&gt;

&lt;p&gt;We already know the one key difference between these two features. WebClient is a non-blocking client and RestTemplate is a blocking client.&lt;/p&gt;

&lt;p&gt;RestTemplate uses Java Servlet API under the hood. Servlet API is a synchronous caller. Because it is synchronous, the thread will block until webclient responds to the request.&lt;/p&gt;

&lt;p&gt;Consequently, Requests waiting for results will increase. This will result in an increase in memory.&lt;/p&gt;

&lt;p&gt;On the other hand, WebClient is an asynchronous non-blocking client. It uses Spring’s reactive framework under the hood. WebClient is a part of the Spring-WebFlux module.&lt;/p&gt;

&lt;p&gt;Spring WebFlux uses &lt;a href="https://github.com/reactor/reactor"&gt;reactor library&lt;/a&gt;. It provides Mono and Flux API to work data sequences. Reactor is a reactive streams library. And, all of its operators support non-blocking back pressure.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example of how to use WebClient in a Spring Boot Application
&lt;/h2&gt;

&lt;p&gt;We can combine the capabilities of Spring Web MVC and Spring WebFlux. In this section, I will create a sample application. This application will call a REST API using WebFlux and we will build a response to show a web page with a list of users.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;RestController&lt;/code&gt; for this example is an API to get a list of users:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
package com.betterjavacode.webclientdemo.controllers;

import com.betterjavacode.webclientdemo.dto.UserDto;
import com.betterjavacode.webclientdemo.managers.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("v1/betterjavacode")
public class UserController
{
    @Autowired
    public UserManager userManager;

    @GetMapping(value = "/users")
    public List getUsers()
    {
        return userManager.getAllUsers();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Controller&lt;/code&gt; class that uses a WebClient to call REST API looks like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.webclientdemo.controllers;

import com.betterjavacode.webclientdemo.clients.UserClient;
import com.betterjavacode.webclientdemo.dto.UserDto;
import com.betterjavacode.webclientdemo.managers.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class MainController
{
    @Autowired
    UserClient userClient;

    @GetMapping(value = "/")
    public String home()
    {
        return "home";
    }

    @GetMapping(value = "/users")
    public String getUsers(Model model)
    {
        List users = userClient.getUsers().block();

        model.addAttribute("userslist", users);
        return "users";
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the important piece of code of UserClient is where we will be using WebClient to call REST API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.webclientdemo.clients;

import com.betterjavacode.webclientdemo.dto.UserDto;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
public class UserClient
{

    private WebClient webClient;

    public UserClient(WebClient.Builder webClientBuilder)
    {
        this.webClient =
                webClientBuilder.baseUrl("http://localhost:8080/v1/betterjavacode/").build();
    }

    public Mono&amp;lt;List&amp;gt; getUsers()
    {
        return this.webClient.get()
                .uri("users")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve().bodyToFlux(UserDto.class).collectList();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above code shows first building the WebClient and then using it to &lt;code&gt;retrieve&lt;/code&gt; response from REST API. retrieve method offers two options of mono or flux. Since we have more than one user to get, we are using flux.&lt;/p&gt;

&lt;p&gt;This shows we can use reactive, non-blocking WebClient which is part of WebFlux in Spring Web MVC framework.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Else Is There in Spring WebClient?
&lt;/h2&gt;

&lt;p&gt;Spring WebClient is part of &lt;code&gt;Spring WebFlux&lt;/code&gt; framework. The major advantage of this API is that the developer doesn’t have to worry about concurrency or threads. WebClient takes care of that.&lt;/p&gt;

&lt;p&gt;WebClient has a built-in HTTP Client library support to perform requests with. That includes Apache HttpComponents, Jetty Reactive HttpClient, or Reactor Netty.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;WebClient.builder()&lt;/code&gt; offers following options:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;uriBuilderFactory&lt;/code&gt; – customized uriBuilderFactory to use base URL&lt;br&gt;
&lt;code&gt;defaultHeader&lt;/code&gt; – Headers for every request&lt;br&gt;
&lt;code&gt;defaultCookie&lt;/code&gt; – Cookies for every request&lt;br&gt;
&lt;code&gt;defaultRequest&lt;/code&gt; – To customize every request&lt;br&gt;
&lt;code&gt;filter&lt;/code&gt; – Client filter for every request&lt;br&gt;
&lt;code&gt;exchangeStrategies&lt;/code&gt; – HTTP Message reader/writer customizations&lt;br&gt;
I already showed &lt;code&gt;retrieve&lt;/code&gt; method in the above code demo.&lt;/p&gt;

&lt;p&gt;WebClient also offers a method &lt;code&gt;exchange&lt;/code&gt; with varients like &lt;code&gt;exchangeToMono and&lt;/code&gt;exchangeToFlux`.&lt;/p&gt;

&lt;p&gt;With &lt;code&gt;attribute()&lt;/code&gt;, we can also add attributes to the request.&lt;/p&gt;

&lt;p&gt;Alternatively, one can use WebClient for synchronous use also. In my example above MainController, I use &lt;code&gt;block&lt;/code&gt; to get the final result. This basically blocks parallel calls till we get the result.&lt;/p&gt;

&lt;p&gt;One key feature that WebClient offers is &lt;code&gt;retryWhen()&lt;/code&gt;. For more resilient system, it is a great feature that you can add while using WebClient.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;        &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;     webClient
        .get()
        .uri(String.join("", "/users", id))
        .retrieve()
        .bodyToMono(UserDto.class)
        .retryWhen(Retry.fixedDelay(5, Duration.ofMillis(100)))
        .block();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;&lt;/code&gt;&lt;br&gt;
&lt;code&gt;retryWhen&lt;/code&gt; takes Retry class as a parameter.&lt;/p&gt;

&lt;p&gt;WebClient also offers a feature for error handling. &lt;code&gt;doOnError()&lt;/code&gt; allows you to handle the error. It is triggered when mono ends with an error. &lt;code&gt;onErrorResume()&lt;/code&gt; is a fallback based on the error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I showed what is Spring WebClient is, how we can use Spring WebClient vs RestTemplate, and what different features it offers.&lt;/p&gt;

</description>
      <category>spring</category>
      <category>webclient</category>
      <category>resttemplate</category>
      <category>java</category>
    </item>
    <item>
      <title>The Complete Guide to use Docker Compose</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sun, 20 Dec 2020 02:13:30 +0000</pubDate>
      <link>https://dev.to/betterjavacode/the-complete-guide-to-use-docker-compose-2gh7</link>
      <guid>https://dev.to/betterjavacode/the-complete-guide-to-use-docker-compose-2gh7</guid>
      <description>&lt;p&gt;In this post, I will cover the complete guide to using docker compose. You can use it to build a multi-container application. But what is a docker compose and why one should use it?&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Docker Compose?
&lt;/h2&gt;

&lt;p&gt;If you don’t know what a docker is, you can read about that here. If you have an application that is running on a docker and if that application is using multiple other services like database, web-server, load balancer, then you can write multiple docker files and run multiple containers. It can be cumbersome to manage these files. And if you have to change something, you might have to change in all files.&lt;/p&gt;

&lt;p&gt;Docker compose solves this problem by allowing you to write a YAML file to define multiple containers in a single file. You write one docker file and build and run that file for all the containers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Installing Docker Compose
&lt;/h2&gt;

&lt;p&gt;Based on the definition from &lt;a href="https://docker.com" rel="noopener noreferrer"&gt;docker&lt;/a&gt;, docker compose is a tool for defining and running multiple Docker containers.&lt;/p&gt;

&lt;p&gt;Depending on your environment, you will have to use the instructions to install docker compose. You will also need docker engine before you can install docker compose. I use the Windows environment, so I will show those instructions here.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Launch Power shell in administrator mode&lt;/li&gt;
&lt;li&gt;Run this command – [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12&lt;/li&gt;
&lt;li&gt;Then run the following command – Invoke-WebRequest “&lt;a href="https://github.com/docker/compose/releases/download/1.27.4/docker-compose-Windows-x86_64.exe%E2%80%9D" rel="noopener noreferrer"&gt;https://github.com/docker/compose/releases/download/1.27.4/docker-compose-Windows-x86_64.exe”&lt;/a&gt; -UseBasicParsing -OutFile $Env:ProgramFiles\Docker\docker-compose.exe
This will install docker compose. Open a new command prompt and type the first command&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;docker-compose -v&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;This should provide the docker-compose version if your installation has run without any issues.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up a Spring Boot application with Docker
&lt;/h2&gt;

&lt;p&gt;To show the power of docker-compose, we will be using a simple To-Do list spring boot app. I will share this app in a GitHub repository along with docker compose file. But this app includes the following applications that we will be using in docker compose:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Spring Boot application&lt;/li&gt;
&lt;li&gt;Java version 8&lt;/li&gt;
&lt;li&gt;MySQL for database&lt;/li&gt;
&lt;li&gt;Keycloak for Authentication&lt;/li&gt;
&lt;li&gt;Postgres for database&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So I won’t show implementing the Spring Boot application. If you want to download this application, you can visit the &lt;a href="https://github.com/yogsma/keycloakdemo" rel="noopener noreferrer"&gt;Github repository&lt;/a&gt; or you can read my previous post &lt;a href="https://betterjavacode.com/programming/spring-boot-application-keycloak" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We will create a docker file for this Spring Boot application and this will run in its own container. Now this application connects to Keycloak and MySQL database for authentication. Keycloak will use Postgres database instead of using the same MySQL database.&lt;/p&gt;

&lt;p&gt;The docker file for the Spring Boot application will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPY ./build/libs/*.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This docker file basically downloads Open JDK 8. It mounts the disk at &lt;code&gt;/tmp&lt;/code&gt;. It copies an application jar file as &lt;code&gt;app.jar&lt;/code&gt;. And of course, it will start the application by running &lt;code&gt;java -jar&lt;/code&gt; .&lt;/p&gt;

&lt;h2&gt;
  
  
  How to write Docker Compose file
&lt;/h2&gt;

&lt;p&gt;Now comes the &lt;code&gt;docker-compose.yml&lt;/code&gt; file. This will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: "3.8"

services:
  web:
    build: .
    ports:
      - "8080:8080"
    depends_on:
      - db
      - keycloak
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://db:3306/todolist?autoReconnect=true&amp;amp;useSSL=false
      SPRING_DATASOURCE_USERNAME: betterjavacode
      SPRING_DATASOURCE_PASSWORD: betterjavacode
      KEYCLOAK_URI: http://keycloak:8180/auth
      REALM: SpringBootKeycloakApp
    networks:
      - common-network
  db:
    image: mysql:5.7
    ports:
      - "3307:3306"
    restart: always
    environment:
      MYSQL_DATABASE: todolist
      MYSQL_USER: betterjavacode
      MYSQL_PASSWORD: betterjavacode
      MYSQL_ROOT_PASSWORD: root
    volumes:
      - db-data:/var/lib/mysql
    networks:
      - common-network
  postgres:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: password
    networks:
      - common-network
  keycloak:
    image: jboss/keycloak
    ports:
      - "8180:8180"
    command: ["-Djboss.socket.binding.port-offset=100"]
    environment:
      DB_VENDOR: POSTGRES
      DB_ADDR: postgres
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_PASSWORD: password
      DB_SCHEMA: public
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: Pa55w0rd
    depends_on:
      - postgres
    networks:
      - common-network
networks:
  common-network:
    driver: bridge
volumes:
  db-data:
    driver: local
  postgres_data:
    driver: local

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line in this docker-compose file is the version of your docker-compose.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;services&lt;/code&gt; define different types of services that we will use to build our docker container. web service uses an image that builds from a docker file. In our case, we are building a docker image of our Spring Boot application. This application will run on port 8080. We also have to make sure to pass the required environment variables. As you see in the file, we are using our database as db and the variable &lt;code&gt;SPRING_DATASOURCE_URL&lt;/code&gt; shows that. db is the name of our database service that our application will connect to.&lt;/p&gt;

&lt;p&gt;Our database service &lt;code&gt;db&lt;/code&gt; runs on host port of 3307, but uses port 3306 (default port) on the container. This is because I have MySQL running on my host machine at port 3306, so to avoid port conflict, I am using 3307.&lt;/p&gt;

&lt;p&gt;We have another database service &lt;code&gt;postgres&lt;/code&gt; in our docker compose file. That uses default ports of 5432 and that’s why not specified here. Keycloak uses postgres as part of this entire application. If you don’t specify postgres, Keycloak will use an in-memory H2 database by default. The problem with an in-memory database is once you stop your container, it will lose all the data. To avoid that, I am using a real database that will save our realm and users’ data.&lt;/p&gt;

&lt;p&gt;Another service, that we are using is &lt;code&gt;keycloak&lt;/code&gt;. This is our IDP for authentication. The service is running on port 8180. It uses the Postgres database to connect to. The command part of keycloak service instructs to run the service on port 8180 in the container instead of default 8080.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;networks&lt;/code&gt; service defines that all these containers are part of the same network &lt;code&gt;common-network&lt;/code&gt; with a driver of type bridge.&lt;br&gt;
To make sure we can use the database, we need to mount the disk volume for both MySQL and Postgres databases. We mount these volumes locally.&lt;/p&gt;

&lt;h2&gt;
  
  
  Running the containers
&lt;/h2&gt;

&lt;p&gt;Now to execute the containers with the application, execute the following command (make sure you build your application)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose up&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will build Docker containers for all our services and start them. Now if we access our application at &lt;code&gt;http://localhost:8080&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyoqkjdp50u5emjne6ka4.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyoqkjdp50u5emjne6ka4.JPG" alt="The Complete Guide To Use Docker Compose - Demo application"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If a user clicks on &lt;code&gt;Get all tasks&lt;/code&gt;, user will see keycloak login screen as below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fa47dcn2y55syst76ktdp.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fa47dcn2y55syst76ktdp.JPG" alt="The Complete Guide to Use Docker Compose - Keycloak Login Screen"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Enter the username and password, and the user will see the tasks for the logged-in user.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0b63w1dgll8lsr3mabne.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F0b63w1dgll8lsr3mabne.JPG" alt="The Complete Guide to Use Docker Compose - Logged in user"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Useful commands
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;docker-compose up&lt;/code&gt; – This command will build the docker containers and start them.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose up -d&lt;/code&gt; – This is a similar command as above, except it will run all the processes in the background.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose stop&lt;/code&gt; – Stop the docker services. This will retain the previous state of containers even after you have stopped the containers.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose start&lt;/code&gt; – Start the docker services&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose logs&lt;/code&gt; – Show the logs from docker containers&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose ps&lt;/code&gt; – List the Docker containers&lt;/p&gt;

&lt;p&gt;&lt;code&gt;docker-compose run&lt;/code&gt; – Run one-off command. Example – &lt;code&gt;docker-compose run web env&lt;/code&gt; – List the environment variables of web service.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advantages of Docker Compose
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;By running most of the services in docker, you don’t have to install those services in your environment.&lt;/li&gt;
&lt;li&gt;It’s easier to collaborate the development environment with other developers by checking in the source in version control with docker-compose.&lt;/li&gt;
&lt;li&gt;Quick and easy configuration. You can run your services across platforms.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Advance use of docker compose
&lt;/h2&gt;

&lt;p&gt;Something I have not covered in this post is using &lt;code&gt;network&lt;/code&gt; as  a service that you can really extend with docker compose. It also allows you to run a load balancer (or reverse proxy like &lt;code&gt;nginx&lt;/code&gt;) and manage the load with multiple hosts.&lt;/p&gt;

&lt;p&gt;Instead of using environment variables, you can also use &lt;code&gt;.env&lt;/code&gt; file for environment variables and load it while starting the containers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I showed how you can use docker compose to run multiple containers with a single docker compose file. It also allows you to easily manage your environment.&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Docker Compose – &lt;a href="https://docs.docker.com/compose/" rel="noopener noreferrer"&gt;docker compose&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Keycloak – &lt;a href="https://github.com/keycloak/keycloak-containers" rel="noopener noreferrer"&gt;Keycloak containers&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>docker</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>7 AWS Services Every Developer Should Know About</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Wed, 18 Nov 2020 17:57:05 +0000</pubDate>
      <link>https://dev.to/betterjavacode/7-aws-services-every-developer-should-know-about-1j3e</link>
      <guid>https://dev.to/betterjavacode/7-aws-services-every-developer-should-know-about-1j3e</guid>
      <description>&lt;p&gt;In this post, I will describe the 7 AWS Services a developer should know about. As a developer, it is important to understand when and how to use these services.&lt;/p&gt;

&lt;p&gt;Even though moving the infrastructure to the cloud movement began in the last decade, it has picked up the speed in the last 5-6 years. As always, Amazon had been leading on this front. Now the most companies use cloud whether AWS, Google, or Microsoft Azure services for cloud infrastructure.&lt;/p&gt;

&lt;p&gt;Amazon Web Services offer a number of services, but we will look at the 7 AWS services only. These services help users to administrator their applications smoothly. If you are building an application and using old on-premise infrastructure, you will be better off moving to the cloud. The dilemma comes what services to use, which Cloud service to choose.&lt;/p&gt;

&lt;h1&gt;
  
  
  7 AWS Services to Know
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Elastic Container Service (ECS)&lt;/li&gt;
&lt;li&gt;Lambda&lt;/li&gt;
&lt;li&gt;Simple Storage Service (S3)&lt;/li&gt;
&lt;li&gt;DynamoDB &lt;/li&gt;
&lt;li&gt;Route53&lt;/li&gt;
&lt;li&gt;Elastic Load Balancer(ELB)&lt;/li&gt;
&lt;li&gt;Kinesis&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Elastic Container Service
&lt;/h1&gt;

&lt;p&gt;ECS is a container orchestration service. What does container orchestration mean?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Basically, you build your application.&lt;/li&gt;
&lt;li&gt;Deploy that application on a docker container.&lt;/li&gt;
&lt;li&gt;Push the docker image to ECR (Elastic Container Repository).&lt;/li&gt;
&lt;li&gt;Build your elastic container service while using the docker image from ECR.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;ECS does a good job of choosing what EC2 instance to use, how to identify a load balancer to use, and how many instances to run for your service.&lt;/p&gt;

&lt;p&gt;ECS easily integrates with other cloud services that Amazon offers. These services include Amazon Route53, Secrets Manager, Identity and Access Management, and Cloudwatch.&lt;/p&gt;

&lt;p&gt;While deploying your service on ECS, you can choose an EC2 container or AWS Fargate container. AWS Fargate is a serverless compute engine that works with both Elastic Container Service or Elastic Kubernetes Service (EKS).&lt;/p&gt;

&lt;p&gt;EC2 is an Elastic Cloud Computing service that offers a server instance. You can choose what you want on your server instance installed.&lt;/p&gt;

&lt;h1&gt;
  
  
  Lambda
&lt;/h1&gt;

&lt;p&gt;If you have heard the word “Serverless”, it is the AWS Lambda that has made it popular. You can write your code without provisioning or managing servers. The selling point of Lambda is that you don’t have to worry about backend infrastructure. Lambda takes care of that, you only pay for the compute time you use. So this makes writing efficient code even more important.&lt;/p&gt;

&lt;p&gt;The alacrity with which Lambda handles running your code, it makes Lambda one of the most useful services. Lambda is definitely the most useful when you want to automate repetitive tasks.&lt;/p&gt;

&lt;p&gt;Running an entire application on Lambda may not be the best idea. If it’s a static website, then surely you can use Lambda. But a scalable and dynamic application, you will be better off using an EC2 instance than Lambda.&lt;/p&gt;

&lt;p&gt;One heuristic to consider to decide when to use Lambda – If you have a code that will not change, but will also perform repetitive tasks without much monitoring efforts, then use Lambda.&lt;/p&gt;

&lt;h1&gt;
  
  
  Simple Storage Service (S3)
&lt;/h1&gt;

&lt;p&gt;S3 is a Simple Cloud Storage. Irrespective of what kind of application you build, you have to store static files somewhere. AWS offers a simple and effective service called S3.&lt;/p&gt;

&lt;p&gt;To understand S3 is to understand a hash table. Usually, when you store any file on S3, the service generates a random string as a key to identify that file. The file is the blob format data.&lt;/p&gt;

&lt;p&gt;S3 is targeted towards application builders to individual users. The advantages of S3 are scalability, high availability, performance, and security. S3 can also be used for redundancy. One thing to remember that you can not use S3 to host a static website, especially if you want to use it with HTTPS.&lt;/p&gt;

&lt;h1&gt;
  
  
  DynamoDB
&lt;/h1&gt;

&lt;p&gt;DyanmoDB is a No-SQL database service. The advantages of DynamoDB over regular DB are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;High performance even at a scale&lt;/li&gt;
&lt;li&gt;A simple API allowing for simple key-value access
Dynamo DB is a partitioned B-Tree Data structure. The performance in DynamoDB remains consistent irrespective of the data you are inserting in it. Key-Value pair makes it easy to access Dyanmo DB.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can get aggregated or sorted data from a regular relational database. But with DynamoDB, your application has to do everything on its own. Once the application fetches the data from DynamoDB, it can get a single data or a contiguous range of data. This is the key point in deciding if you want to use DynamoDB or not.&lt;/p&gt;

&lt;h1&gt;
  
  
  Route53
&lt;/h1&gt;

&lt;p&gt;Route53 as the name suggests is a DNS service that translates a domain name to IP address. When a request comes from an application to AWS infrastructure, Route53 translates that request to either load balancers or EC2 instance or S3 bucket.&lt;/p&gt;

&lt;p&gt;Route53 may not have many advantages over any other infrastructure, but as a developer knowing about Route53 is important. Once you deploy your application in AWS, you will need to make sure it is accessible to users. From a network perspective, understanding Route53 is important.&lt;/p&gt;

&lt;p&gt;Route53 integrates well with ELB (Elastic Load Balancer).&lt;/p&gt;

&lt;h1&gt;
  
  
  ELB
&lt;/h1&gt;

&lt;p&gt;ELB is an elastic load balancer service. It offers a load balancer for application and for the network. So we can say application load balancer (ALB) or network load balancer (NLB).&lt;/p&gt;

&lt;p&gt;Application load balancer basically routes the traffic from the internet to your application and vice versa. ALBs offer different features like routing rules, sticky sessions, authentications.&lt;/p&gt;

&lt;p&gt;Network load balancers route the network packets. NLB is a network router and not an HTTP request router.&lt;/p&gt;

&lt;p&gt;Both NLBs and ALBs support TLS/HTTPS and integrates with AWS Certificate Manager. NLBs and ALBs don’t validate certificates, but since these load balancers run in a VPC, there is a protection from spoofing and man-in-the-middle attack.&lt;/p&gt;

&lt;p&gt;One disadvantage of ALBs is that it adds a few milliseconds to each request, increasing the latency in the process. AWS handles scaling ALB automatically based on the demand for your service.&lt;/p&gt;

&lt;h1&gt;
  
  
  Kinesis
&lt;/h1&gt;

&lt;p&gt;Kinesis is a streaming service. It basically collects, processes, and analyzes real-time data. Once the data arrives in the streaming service, you can build an event to handle the data. Kinesis steam is a highly durable linked list.&lt;/p&gt;

&lt;p&gt;You can have multiple applications consuming data from Kinesis. As data streaming getting more and more popular, kinesis offers a lot of flexibility.&lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;There are a lot of other AWS services like SQS, Cloud Formation, Cognito, API Gateway, Step Functions, etc. Here I described 7 AWS services that you will end up using the most frequently. Also, I want to thank Daniel Vassallo and his insightful book &lt;a href="https://gumroad.com/dvassallo#MsVlG"&gt;The Good Parts of AWS&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Original post for this was published on my blog &lt;a href="https://betterjavacode.com/programming/7-aws-services-every-developer-should-know-about"&gt;betterjavacode &lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>lambda</category>
      <category>dynamodb</category>
      <category>amazon</category>
    </item>
    <item>
      <title>How to Use Keycloak With a Spring Boot Application</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Fri, 25 Sep 2020 23:25:42 +0000</pubDate>
      <link>https://dev.to/betterjavacode/how-to-use-keycloak-with-a-spring-boot-application-3385</link>
      <guid>https://dev.to/betterjavacode/how-to-use-keycloak-with-a-spring-boot-application-3385</guid>
      <description>&lt;p&gt;In this post, I will show how to use Keycloak in a Spring Boot application. Before we use Keycloak, we will cover some basics about what Keycloak is and why we use it.&lt;/p&gt;

&lt;p&gt;To get started with this demo, you will need the following things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A Code Editor – IntelliJ&lt;/li&gt;
&lt;li&gt;Database – MySQL&lt;/li&gt;
&lt;li&gt;Keycloak&lt;/li&gt;
&lt;li&gt;Java 8&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is Keycloak?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://keycloak.org" rel="noopener noreferrer"&gt;Keycloak&lt;/a&gt; is an open-source identity and access management solution for modern applications and services. Keycloak provides both SAML and OpenID protocol solutions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why do we use Keycloak?
&lt;/h2&gt;

&lt;p&gt;As mentioned, Keycloak provides identity and access management, it is also open source. SAML and OpenID protocols are industry standards. Building an application that is integrated with Keycloak will only provide you a more secure and stable solution. There are definitely other solutions available like Gluu, Shibboleth, WSO2.&lt;/p&gt;

&lt;p&gt;For this post, we will be using Keycloak.&lt;/p&gt;

&lt;h2&gt;
  
  
  Securing Spring Boot Application with Keycloak
&lt;/h2&gt;

&lt;p&gt;There are two parts in this demo. One is about Keycloak. The second is about securing the Spring Boot Application with Keycloak.&lt;/p&gt;

&lt;h3&gt;
  
  
  Install Keycloak
&lt;/h3&gt;

&lt;p&gt;Download the &lt;a href="https://keycloak.org" rel="noopener noreferrer"&gt;Keycloak&lt;/a&gt; on your machine.  Unzip the downloaded file and run the server with the following command from bin directory on your command prompt (Note – I’m on a windows machine):&lt;/p&gt;

&lt;p&gt;&lt;code&gt;standalone.bat -Djboss.socket.binding.port-offset=100&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will start the Wildfly server for your Keycloak on your local machine. We can access the server by executing the URL &lt;code&gt;http://localhost:8180&lt;/code&gt;. If you just use standalone.bat to execute without that parameter, the server will run on the port &lt;code&gt;8080&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fif4jr0o578chezj1jwk0.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fif4jr0o578chezj1jwk0.JPG" alt="Keycloak First Screen"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you start the server, the first thing you will have to do is to create an admin user. We will create a user admin and password d#n3q2b .&lt;/p&gt;

&lt;p&gt;Now we will access the administration console and enter our user details. Once we login as an admin user, we will see the first screen as below:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgaxxkcgagv53f4r2j047.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fgaxxkcgagv53f4r2j047.JPG" alt="Keycloak Homescreen"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Adding Application
&lt;/h3&gt;

&lt;p&gt;Initial screen shows the default realm. For our demo purposes, we will create a new realm &lt;code&gt;SpringBootKeycloakApp&lt;/code&gt;. In this realm, we will add our Spring Boot application as a client. Create a new client on Clients tab. We will name our client application as SpringBootApp.&lt;/p&gt;

&lt;p&gt;Now in settings, we will add redirect url for our Spring Boot Application. This is the URL where Keycloak will redirect to our app after authentication. Also, we are using openid connect as a protocol as part of this implementation.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flssmsobzxm6cb4moovkw.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flssmsobzxm6cb4moovkw.JPG" alt="Keycloak Settings"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Adding User
&lt;/h3&gt;

&lt;p&gt;Now we will add a user that we will use to authenticate. We will use this user to login to our sample Spring Boot application.&lt;/p&gt;

&lt;p&gt;Add a role that you want for this user &lt;code&gt;ROLE_User&lt;/code&gt; on the roles tab in Keycloak. Once that is done, let’s go to the Users tab and add a new user.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk6srawbn4ai8gzsabqwc.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fk6srawbn4ai8gzsabqwc.JPG" alt="Add User"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On the Role Mappings tab, make sure to add the newly created role for this user.&lt;/p&gt;
&lt;h2&gt;
  
  
  Create A Spring Boot Application
&lt;/h2&gt;

&lt;p&gt;Now, we will create a simple Spring Boot application that will use Keycloak for security. As part of this application, we will be showing a list of to-do list tasks for the user who will authenticate with the application.&lt;/p&gt;

&lt;p&gt;To build this app, we need the following dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    implementation 'org.keycloak:keycloak-spring-boot-starter'
    runtimeOnly 'mysql:mysql-connector-java'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation 'org.springframework.security:spring-security-test'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see we are using &lt;code&gt;spring-boot&lt;/code&gt; and &lt;code&gt;spring-security&lt;/code&gt; along with &lt;code&gt;keycloak-spring-boot-starter&lt;/code&gt; dependency.&lt;/p&gt;

&lt;p&gt;The keycloak dependency includes Keycloak client adapters. We will use these adapters for authentication purposes. They will replace our standard Spring Security adapters. To make sure this &lt;code&gt;keycloak-spring-boot-starter&lt;/code&gt; dependency works correctly, we will need one more dependency to be added in our gradle file as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dependencyManagement {
    imports {
        mavenBom "org.keycloak.bom:keycloak-adapter-bom:11.0.2"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To read more about this, you can visit the official documentation of &lt;a href="https://keycloak.org" rel="noopener noreferrer"&gt;keycloak&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Our Controller class will have two important methods, one to get the home page which will be accessible for anyone, and another getting the list of tasks which will be accessible to only authenticated users with a role ROLE_User.  The code for this TaskController will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.keycloakdemo.keycloakdemo.controllers;

import com.betterjavacode.keycloakdemo.keycloakdemo.dto.TaskDto;
import com.betterjavacode.keycloakdemo.keycloakdemo.managers.TaskManager;
import org.keycloak.KeycloakSecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class TaskController
{
    private final HttpServletRequest request;

    @Autowired
    public TaskController(HttpServletRequest request)
    {
        this.request = request;
    }

    @Autowired
    private TaskManager taskManager;

    @GetMapping(value="/")
    public String home()
    {
        return "index";
    }

    @GetMapping(value="/tasks")
    public String getTasks(Model model)
    {
        List tasks = taskManager.getAllTasks();
        model.addAttribute("tasks", tasks);
        model.addAttribute("name", getKeycloakSecurityContext().getIdToken().getGivenName());

        return "tasks";
    }

    private KeycloakSecurityContext getKeycloakSecurityContext()
    {
        return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    }

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this controller class, we use &lt;code&gt;TaskManager&lt;/code&gt; to get all tasks. I will explain  &lt;code&gt;KeyCloakSecurityContext&lt;/code&gt; when I will show about &lt;code&gt;SecurityConfig&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  With or without Spring-Security
&lt;/h2&gt;

&lt;p&gt;We can leverage this application and use Keycloak for authentication with or without &lt;code&gt;Spring-Security&lt;/code&gt;. As part of this demo, we are using &lt;code&gt;Spring-Security&lt;/code&gt;. To use the same application without Spring-Security, you can just remove the Spring-Security dependency and add security configuration through &lt;code&gt;application.properties&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;We will need the following properties in &lt;code&gt;application.properties&lt;/code&gt; to use Keycloak for authentication in this app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;keycloak.auth-server-url=http://localhost:8180/auth
keycloak.realm=SpringBootKeycloakApp
keycloak.resource=SpringBootApp
keycloak.public-client=true
keycloak.principal-attribute=preferred_username

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we wanted to use this application without Spring-Security, we will need the following two properties also:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;keycloak.security-constraints[0].authRoles[0]=ROLE_User
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/tasks
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we are using &lt;code&gt;Spring-Security&lt;/code&gt;, we will configure the security configuration through a Java class &lt;code&gt;SecurityConfig&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This SecurityConfig class will extend &lt;code&gt;KeyCloakWebSecurityConfigurerAdapter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our configure method will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        super.configure(httpSecurity);
        httpSecurity.authorizeRequests()
                .antMatchers("/tasks").hasRole("User")
                .anyRequest().permitAll();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically any requests coming to /tasks endpoint, should have user role as ROLE_User. The prefix of ROLE_ is assumed here. Other than any other request will be permitted without any authorization. In this case, we will be calling our index page.&lt;/p&gt;

&lt;p&gt;We will be using annotation &lt;code&gt;@KeyCloakConfiguration&lt;/code&gt; which is basically covers &lt;code&gt;@Configuration&lt;/code&gt; and &lt;code&gt;@EnableWebSecurity&lt;/code&gt; annotations.&lt;/p&gt;

&lt;p&gt;Since our &lt;code&gt;SecurityConfig&lt;/code&gt; extends &lt;code&gt;KeycloakWebSecurityConfigurerAdapter&lt;/code&gt;, we have to implement sessionAuthenticationStrategy and httpSessionManager. We will also have to register our idp Keycloak with Spring Security Authentication Manager.&lt;/p&gt;

&lt;p&gt;So our SecurityConfig will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.keycloakdemo.keycloakdemo.config;

import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.management.HttpSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;


@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder)
    {
        SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
        simpleAuthorityMapper.setPrefix("ROLE_");

        KeycloakAuthenticationProvider keycloakAuthenticationProvider =
                keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(simpleAuthorityMapper);
        authenticationManagerBuilder.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy ()
    {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Bean
    @Override
    @ConditionalOnMissingBean(HttpSessionManager.class)
    protected HttpSessionManager httpSessionManager()
    {
        return new HttpSessionManager();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        super.configure(httpSecurity);
        httpSecurity.authorizeRequests()
                .antMatchers("/tasks").hasRole("User")
                .anyRequest().permitAll();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So Spring Security uses roles in upper case like ROLE_USER and always use ROLE_ prefix. To handle that, I have added a user with a role ROLE_User in Keycloak, but we will only verify a prefix as our http configuration will verify the role anyhow.&lt;/p&gt;

&lt;p&gt;Since we will be authenticating with Keycloak, we will need a session for user’s state. We are using &lt;code&gt;RegisterSessionAuthenticationStrategy&lt;/code&gt; here. &lt;code&gt;HttpSessionManager&lt;/code&gt; is a conditional bean because Keycloak already implements that bean.&lt;/p&gt;

&lt;p&gt;To implement Keycloak Spring Boot adapter, we will add a &lt;code&gt;KeyCloakSpringBootConfigResolver&lt;/code&gt; bean as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.keycloakdemo.keycloakdemo.config;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeycloakConfig
{
    @Bean
    public KeycloakSpringBootConfigResolver keycloakSpringBootConfigResolver()
    {
        return new KeycloakSpringBootConfigResolver();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have not shown the rest of the application build, but the code is available on &lt;a href="https://github.com/yogsma/keycloakdemo" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt; for this project.&lt;/p&gt;

&lt;h2&gt;
  
  
  Demo of the application
&lt;/h2&gt;

&lt;p&gt;Run our keycloak application, it will be running on &lt;a href="http://localhost:8180" rel="noopener noreferrer"&gt;http://localhost:8180&lt;/a&gt;. Our Spring Boot application will be running at &lt;a href="http://localhost:8080" rel="noopener noreferrer"&gt;http://localhost:8080&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Our first screen of the Spring Boot application will look like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwmhucg5zzdzcjmz1psvm.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwmhucg5zzdzcjmz1psvm.JPG" alt="ToDoList Tasks"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now if a user clicks on Get all tasks, he will be redirected to Keycloak login screen as below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyxz1j345c3gb1p6bq3tf.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyxz1j345c3gb1p6bq3tf.JPG" alt="Keycloak Login Screen"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, I will enter my user betterjavacode username and password and it will show us our list of tasks as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftjwsdg2ee0tpgdr0jzua.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftjwsdg2ee0tpgdr0jzua.JPG" alt="List of tasks"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Authentication Flow
&lt;/h2&gt;

&lt;p&gt;When the user clicks on Get all tasks, the user is redirected to Spring Security’s sso/login endpoint which KeycloakSpringBootConfigResolver handles and sends an authorization code flow request to Keycloak&lt;/p&gt;

&lt;p&gt;&lt;code&gt;http://localhost:8180/auth/realms/SpringBootKeycloakApp/protocol/openid-connect/auth?response_type=code&amp;amp;client_id=SpringBootApp&amp;amp;redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fsso%2Flogin&amp;amp;state=70bd4e28-89e6-43b8-8bea-94c6d057a5cf&amp;amp;login=true&amp;amp;scope=openid&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Keycloak will process the request to respond with a session code and show the login screen.&lt;/p&gt;

&lt;p&gt;Once the user enters credentials and keycloak validates those, it will respond with an authorization code, and this code is exchanged for a token, and the user is logged in.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post, I showed how to secure your Spring Boot application using Keycloak as an identity provider.&lt;/p&gt;

&lt;p&gt;The original post for this was posted on my blog &lt;a href="https://betterjavacode.com/programming/spring-boot-application-keycloak" rel="noopener noreferrer"&gt;betterjavacode&lt;/a&gt;&lt;/p&gt;

</description>
      <category>keycloak</category>
      <category>springboot</category>
      <category>java</category>
      <category>springsecurity</category>
    </item>
    <item>
      <title>How to use Basic Authentication with Rest Template in Spring Boot</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Tue, 18 Aug 2020 02:16:24 +0000</pubDate>
      <link>https://dev.to/betterjavacode/how-to-use-basic-authentication-with-rest-template-in-spring-boot-20o9</link>
      <guid>https://dev.to/betterjavacode/how-to-use-basic-authentication-with-rest-template-in-spring-boot-20o9</guid>
      <description>&lt;p&gt;In this post, I will show how to use Rest Template to consume RESTful API secured with Basic Authentication. As part of this post, I will show how to build a REST API that is secured with Basic Authentication.&lt;/p&gt;

&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;Basic Authentication is one of the mechanisms that you can use to secure your REST API. In my previous post, I showed how to secure REST API with &lt;a href="https://dev.to/betterjavacode/json-web-token-how-to-secure-spring-boot-rest-api-3cg2"&gt;Json Web Token&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Secure a REST API with Basic Authentication
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Configure a REST API
&lt;/h3&gt;

&lt;p&gt;Firstly, we will show a simple REST API to create users or retrieve users from the database. Then, we will secure this REST API with a Basic Authentication mechanism. Lastly, we will show how to use Basic Authentication with Rest Template to call this REST API.&lt;/p&gt;

&lt;p&gt;Our REST controller class for this API to create or retrieve users will look like below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo.controllers;

import com.betterjavacode.restdemo.dto.UserDto;
import com.betterjavacode.restdemo.managers.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController
{
    @Autowired
    private UserManager userManager;

    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity&amp;lt;List&amp;lt;UserDto&amp;gt;&amp;gt; listAllUsers()
    {
        List&amp;lt;UserDto&amp;gt; users = userManager.getAllUsers();
        if(users.isEmpty())
        {
            return new ResponseEntity&amp;lt;List&amp;lt;UserDto&amp;gt;&amp;gt;(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity&amp;lt;&amp;gt;(users, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces =
            MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;UserDto&amp;gt; getUser(@PathVariable("id") long id)
    {
        UserDto userDto = userManager.getUser(id);
        if(userDto == null)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity&amp;lt;&amp;gt;(userDto, HttpStatus.OK);
    }


    @RequestMapping(value = "/user/", method= RequestMethod.POST)
    public ResponseEntity&amp;lt;UserDto&amp;gt; createUser(@RequestBody UserDto userDto)
    {
        UserDto user = userManager.createUser(userDto);

        return new ResponseEntity&amp;lt;&amp;gt;(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{id}", method=RequestMethod.DELETE)
    public ResponseEntity&amp;lt;UserDto&amp;gt; deleteUser(@PathVariable("id") long id)
    {
        UserDto user = userManager.getUser(id);

        if(user == null)
        {
            return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NOT_FOUND);
        }

        userManager.deleteUser(id);

        return new ResponseEntity&amp;lt;&amp;gt;(HttpStatus.NO_CONTENT);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Our database model class for User will look like below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo.models;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "User")
@Table(name = "users")
public class User implements Serializable
{
    private static final long serialVersionUID = 20200816121023L;

    public User()
    {

    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id", nullable=false)
    private long id;

    @Column(name="firstname", length=100)
    private String firstname;

    @Column(name="lastname", length=100)
    private String lastname;

    @Column(name="email", length=100)
    private String email;

    @Column(name="role", length=45)
    private String role;

    @Column(name="enabled")
    private boolean enabled;

    public long getId ()
    {
        return id;
    }

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

    public String getFirstname ()
    {
        return firstname;
    }

    public void setFirstname (String firstname)
    {
        this.firstname = firstname;
    }

    public String getLastname ()
    {
        return lastname;
    }

    public void setLastname (String lastname)
    {
        this.lastname = lastname;
    }

    public String getEmail ()
    {
        return email;
    }

    public void setEmail (String email)
    {
        this.email = email;
    }

    public String getRole ()
    {
        return role;
    }

    public void setRole (String role)
    {
        this.role = role;
    }

    public boolean isEnabled ()
    {
        return enabled;
    }

    public void setEnabled (boolean enabled)
    {
        this.enabled = enabled;
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Just to make sure we understand here that, we are using a DTO object UserDto to create and retrieve the data from the database. &lt;code&gt;User&lt;/code&gt; is our database model object.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;UserDto&lt;/code&gt; object will be as follows:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo.dto;

import com.betterjavacode.restdemo.models.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto
{
    private String firstname;
    private String lastname;
    private String email;

    public UserDto(){}

    public UserDto(User user)
    {
        this.setEmail(user.getEmail());
        this.setFirstname(user.getFirstname());
        this.setLastname(user.getLastname());
    }

    public String getFirstname ()
    {
        return firstname;
    }

    public void setFirstname (String firstname)
    {
        this.firstname = firstname;
    }

    public String getLastname ()
    {
        return lastname;
    }

    public void setLastname (String lastname)
    {
        this.lastname = lastname;
    }

    public String getEmail ()
    {
        return email;
    }

    public void setEmail (String email)
    {
        this.email = email;
    }

}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Once we configure our application properties and create the required database table, we will start the application.&lt;/p&gt;

&lt;p&gt;Now if we execute the API through a client like Postman, we will be able to retrieve or create the User object.&lt;/p&gt;

&lt;p&gt;The goal is to secure this API.&lt;/p&gt;

&lt;p&gt;So add &lt;code&gt;Spring-Security&lt;/code&gt; in our project build.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;implementation "org.springframework.boot:spring-boot-starter-security"&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, if we add the annotation &lt;code&gt;@EnableWebSecurity&lt;/code&gt; in our main application class like below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@SpringBootApplication
@EnableWebSecurity
public class RestdemoApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(RestdemoApplication.class, args);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and if we access the API to create user, we will get 401 unauthorized error like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp375xlie7d2skic66zib.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fp375xlie7d2skic66zib.JPG" alt="Unauthorized Access of REST API"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Basic Authentication
&lt;/h3&gt;

&lt;p&gt;Traditionally, access to REST API will happen on the server-side once the user has logged in with authentication.&lt;/p&gt;

&lt;p&gt;Basic authentication provides one of the ways to secure REST API. It’s not the most secure way compared to OAuth or JWT based security. In Basic Authentication, a client sends Base64 encoded credentials with each request using HTTP Authorization Header.&lt;/p&gt;

&lt;p&gt;The client will send the Authorization header with each request. There is always a possibility of compromising these credentials even when they are Base64 encoded. To avoid that, we can use HTTPS.&lt;/p&gt;

&lt;p&gt;Now from our implementation perspective, we will add a &lt;code&gt;SecurityConfig&lt;/code&gt; class to configure security for our REST API.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                .csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception
    {
        auth.inMemoryAuthentication()
                .withUser("adminuser")
                .password("{noop}adminpassword")
                .roles("USER");
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;code&gt;configure&lt;/code&gt; method in this class will configure basic authentication and every request coming to our controller will need to be authorized.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;configureGlobal&lt;/code&gt; method will add authentication of the incoming request. The requests coming through the controller will be validated for these credentials that we have configured for in-memory authentication.&lt;/p&gt;

&lt;p&gt;WARNING – This is not the most secure way to secure your API. Definitely not with in-memory authentication. Do not use it in production.&lt;/p&gt;

&lt;p&gt;Now if we execute REST API through POSTMAN, we will see the successful response as below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffqwmkk0von9h5ew78fw1.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ffqwmkk0von9h5ew78fw1.JPG" alt="Secure REST API with Basic Authentication"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Rest Template with Basic Authentication Example
&lt;/h2&gt;

&lt;p&gt;Initially, we used POSTMAN as a client to call our REST APIs. But in a real scenario, we won’t be using POSTMAN, you will have to call these APIs programmatically.&lt;/p&gt;

&lt;p&gt;We will create a class &lt;code&gt;RestClient&lt;/code&gt; and that will call our APIs while building Basic Authentication.&lt;/p&gt;

&lt;p&gt;While using &lt;code&gt;RestTemplate&lt;/code&gt; that Spring Boot provides, you need to pass HttpHeaders with a &lt;code&gt;RequestEntity&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

private static HttpHeaders getHeaders ()
    {
        String adminuserCredentials = "adminuser:adminpassword";
        String encodedCredentials =
                new String(Base64.encodeBase64(adminuserCredentials.getBytes()));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Basic " + encodedCredentials);
        httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        return httpHeaders;
    }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We use &lt;code&gt;exchange&lt;/code&gt; method from &lt;code&gt;RestTemplate&lt;/code&gt; to call our API and &lt;code&gt;HttpHeaders&lt;/code&gt; that contain Basic Authentication.&lt;/p&gt;

&lt;p&gt;The whole class  RestClient will look like below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package com.betterjavacode.restdemo;


import com.betterjavacode.restdemo.dto.UserDto;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONObject;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

public class RestClient
{
    public static final String REST_SERVICE_URL = "http://localhost:8080/user/";

    private static HttpHeaders getHeaders ()
    {
        String adminuserCredentials = "adminuser:adminpassword";
        String encodedCredentials =
                new String(Base64.encodeBase64(adminuserCredentials.getBytes()));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Basic " + encodedCredentials);
        httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        return httpHeaders;
    }

    private static void listAllUsers()
    {
        System.out.println("Getting all users");
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders httpHeaders = getHeaders();

        HttpEntity&amp;lt;String&amp;gt; httpEntity = new HttpEntity&amp;lt;&amp;gt;(httpHeaders);

        ResponseEntity&amp;lt;List&amp;gt; responseEntity = restTemplate.exchange(REST_SERVICE_URL,
                HttpMethod.GET, httpEntity, List.class);

        if(responseEntity.hasBody())
        {
            List&amp;lt;LinkedHashMap&amp;lt;String, Object&amp;gt;&amp;gt; users = responseEntity.getBody();

            if(users != null)
            {
                for(LinkedHashMap&amp;lt;String, Object&amp;gt; userMap: users)
                {
                    System.out.println("User is " + userMap.get("firstname") + " " + userMap.get(
                            "lastname"));
                }
            }
        }
        else
        {
            System.out.println("User not found");
        }

    }

    public static void main (String[] args)
    {
        listAllUsers();

        getUser(1);
    }



    private static void getUser(long id)
    {
        System.out.println("Getting a user ");

        String restUrl = REST_SERVICE_URL  + id;

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders httpHeaders = getHeaders();

        HttpEntity&amp;lt;String&amp;gt; httpEntity = new HttpEntity&amp;lt;&amp;gt;(httpHeaders);

        ResponseEntity&amp;lt;String&amp;gt; responseEntity = restTemplate.exchange(restUrl,
                HttpMethod.GET, httpEntity, String.class);

        if(responseEntity.hasBody())
        {
            JSONObject jsonObject = new JSONObject(responseEntity.getBody());

            System.out.println(jsonObject.get("firstname"));
            System.out.println(jsonObject.get("lastname"));
        }
        else
        {
            System.out.println("User not found");
        }

    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now if we execute the program, we will see the output as below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fprbn6m3969gsado2zk08.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fprbn6m3969gsado2zk08.JPG" alt="Using Rest Template with Basic Authentication Response"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this post, we showed how to secure REST API with Basic Authentication. The original post was published on my blog &lt;a href="https://betterjavacode.com" rel="noopener noreferrer"&gt;Betterjavacode&lt;/a&gt;&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>java</category>
      <category>rest</category>
      <category>api</category>
    </item>
    <item>
      <title>Json Web Token: How to secure Spring Boot REST API</title>
      <dc:creator>Yogesh Mali</dc:creator>
      <pubDate>Sat, 08 Aug 2020 05:50:30 +0000</pubDate>
      <link>https://dev.to/betterjavacode/json-web-token-how-to-secure-spring-boot-rest-api-3cg2</link>
      <guid>https://dev.to/betterjavacode/json-web-token-how-to-secure-spring-boot-rest-api-3cg2</guid>
      <description>&lt;p&gt;In this post, I will show how to secure your spring boot based REST API. It has been more of a trend to secure REST APIs to avoid any unnecessary calls to public APIs. We will be using some Spring boot features for Spring security along with JSON WebTokens for authorization.&lt;/p&gt;

&lt;h3&gt;
  
  
  User flow in this case is
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;User logs in&lt;/li&gt;
&lt;li&gt;We validate user credentials&lt;/li&gt;
&lt;li&gt;A token is sent back to user agent.&lt;/li&gt;
&lt;li&gt;User tries to access a protected resource.&lt;/li&gt;
&lt;li&gt;User sends JWT when accessing the protected resource. We validate JWT.&lt;/li&gt;
&lt;li&gt;If JWT is valid, we allow the user to access the resource.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;JSON WebTokens, known as JWTs are used for forming authorization for users. This helps us to build secure APIs and it is also easy to scale. During authentication, a JSON web token is returned. Whenever the user wants to access a protected resource, the browser must send JWTs in the Authorization header along with the request. One thing to understand here is that it is a good security practice to secure REST API.&lt;/p&gt;

&lt;p&gt;Basically, we will show&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Verify JSON WebToken&lt;/li&gt;
&lt;li&gt;Validate the signature&lt;/li&gt;
&lt;li&gt;Check the client permissions&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What you will need?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Java 8,&lt;/li&gt;
&lt;li&gt;MySQL Database&lt;/li&gt;
&lt;li&gt;IntelliJ Editor&lt;/li&gt;
&lt;li&gt;Gradle&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note - This won't be a full-fledged app, but REST APIs based on Spring boot, Spring security.&lt;/p&gt;

&lt;h2&gt;
  
  
  Spring Boot Based REST API
&lt;/h2&gt;

&lt;p&gt;I will be securing REST API for company that I created in this blog post &lt;a href="https://betterjavacode.com/2018/02/25/caching-how-to-use-redis-caching-with-spring-boot/" rel="noopener noreferrer"&gt;REST API&lt;/a&gt;. This API also includes caching. A user will try to access &lt;code&gt;/cachedemo/v1/companies/&lt;/code&gt; and since APIs are protected, he will get a response like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fye1vhpd8wezqkak4ykce.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fye1vhpd8wezqkak4ykce.JPG" alt="Secure REST API - Forbidden"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will implement how to protect this API and how to access it when it is protected.&lt;/p&gt;

&lt;h4&gt;
  
  
  Adding User and User registration
&lt;/h4&gt;

&lt;p&gt;Since we want to add authorization for APIs, we will need where the user is able to log in and send credentials. These credentials will be validated and a token will be generated. This token then will be transmitted in a request to an API call. The token will be validated in the Spring security authorization filter that we will add. If a valid token, the user will be able to access the API.&lt;/p&gt;

&lt;h4&gt;
  
  
  Create a user model
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.models;

import javax.persistence.*;
import java.io.Serializable;

@Entity(name = "User")
@Table(name = "user")
public class User implements Serializable
{
    public User()
    {

    }

    @Id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)
    private long id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    public long getId()
    {
        return id;
    }

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

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will add a controller where a user can register with its details for &lt;code&gt;username&lt;/code&gt; and &lt;code&gt;password&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.resources;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/cachedemo/v1/users")
public class UserController
{
    private UserRepository userRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PostMapping("/signup")
    public void signUp(@RequestBody User user)
    {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when we POST a request to &lt;code&gt;/cachedemo/v1/users/signup&lt;/code&gt; , a user will be saved in the database. &lt;code&gt;Password&lt;/code&gt; for the user will be saved in encrypted format as we are using &lt;code&gt;BCryptPasswordEncoder&lt;/code&gt;. We will show how a user can log in to create a token.&lt;/p&gt;

&lt;h4&gt;
  
  
  User Login
&lt;/h4&gt;

&lt;p&gt;To handle user login, we will add an &lt;code&gt;AuthenticationFilter&lt;/code&gt; which will get added in FilterChain and Spring boot will handle the execution of it appropriately. This filter will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.SpringAppCache;


import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    private AuthenticationManager authenticationManager;

    public AuthenticationFilter(AuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
        setFilterProcessesUrl("/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException
    {
        try
        {
            com.betterjavacode.models.User creds = new ObjectMapper().readValue(request.getInputStream(), com.betterjavacode .models.User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword(),new ArrayList&amp;lt;&amp;gt;()));
        }
        catch(IOException e)
        {
            throw new RuntimeException("Could not read request" + e);
        }
    }

    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Authentication authentication)
    {
        String token = Jwts.builder()
                .setSubject(((User) authentication.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 864_000_000))
                .signWith(SignatureAlgorithm.HS512, "SecretKeyToGenJWTs".getBytes())
                .compact();
        response.addHeader("Authorization","Bearer " + token);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically, a user will send credentials in a request to URL ending with /login . This filter will help to authenticate the user, if there is successful authentication, a Token will be added in response header with the key Authorization.&lt;/p&gt;

&lt;h4&gt;
  
  
  Token Validation and Authorization
&lt;/h4&gt;

&lt;p&gt;We add another filter AuthorizationFilter to validate the token that we passed through AuthenticationFilter earlier. This filter will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.SpringAppCache;

import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class AuthorizationFilter extends BasicAuthenticationFilter
{
    public AuthorizationFilter(AuthenticationManager authenticationManager)
    {
        super(authenticationManager);
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException
    {
        String header = request.getHeader("Authorization");
        if(header == null || !header.startsWith("Bearer"))
        {
            filterChain.doFilter(request,response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        if(token != null)
        {
            String user = Jwts.parser().setSigningKey("SecretKeyToGenJWTs".getBytes())
                    .parseClaimsJws(token.replace("Bearer",""))
                    .getBody()
                    .getSubject();
            if(user != null)
            {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList&amp;lt;&amp;gt;());
            }
            return null;
        }
        return null;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the validation of the token is successful, a user is returned and assigned to a security context.&lt;/p&gt;

&lt;p&gt;To enable Spring security, we will add a new class WebSecurityConfiguration with annotation &lt;code&gt;@EnableWebSecurity&lt;/code&gt;. This class will extend the standard &lt;code&gt;WebSecurityConfigurerAdapter&lt;/code&gt;. In this class, we will restrict our APIs and also add some whitelisted URLs that we will need access without any authorization token. This will look like below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.SpringAppCache;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserDetailsService userDetailsService;

    private static final String[] AUTH_WHITELIST = {
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    public WebSecurityConfiguration(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder)
    {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }


    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .antMatchers(HttpMethod.POST, "/cachedemo/v1/users/signup").permitAll()
                .anyRequest().authenticated()
                .and().addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception
    {
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In method configure we have restricted most APIs, only allowing Swagger URLs and signup URL. We also add filters to HttpSecurity. We will add our own &lt;code&gt;UserDetailsServiceImpl&lt;/code&gt; class to validate user credentials.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.betterjavacode.services;

import com.betterjavacode.models.User;
import com.betterjavacode.repositories.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class UserDetailsServiceImpl implements UserDetailsService
{
    private UserRepository userRepository;

    public UserDetailsServiceImpl(UserRepository userRepository)
    {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        User user = userRepository.findByUsername(username);
        if(user == null)
        {
            throw new UsernameNotFoundException(username);
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Demo
&lt;/h4&gt;

&lt;p&gt;With the all the code changes, now we are ready to create a user, login and access secured REST APIs. From the image above, a user gets Access Denied error for accessing secured APIs. To demo this, I have already registered a user with username &lt;code&gt;test1&lt;/code&gt; and password test@123.&lt;/p&gt;

&lt;p&gt;The POST request for login will give us Authorization token in response. Now using this token in our GET request to retrieve companies data. This GET request will look like below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzta4ozdbkc5hsyuqkpvo.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fzta4ozdbkc5hsyuqkpvo.JPG" alt="Securing REST API - access"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this way, we showed how to secure REST API using JSON web token.&lt;/p&gt;

&lt;p&gt;The original blog post was posted on my blog &lt;a href="https://betterjavacode.com/java/securing-spring-boot-rest-api" rel="noopener noreferrer"&gt;betterjavacode&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
    </item>
  </channel>
</rss>
