<?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: Anirban</title>
    <description>The latest articles on DEV Community by Anirban (@anirban99).</description>
    <link>https://dev.to/anirban99</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%2F579841%2Facf7fb6c-ddf5-4880-9b45-a76aeb1a712a.png</url>
      <title>DEV Community: Anirban</title>
      <link>https://dev.to/anirban99</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/anirban99"/>
    <language>en</language>
    <item>
      <title>Build REST API with Spring Boot and Kotlin</title>
      <dc:creator>Anirban</dc:creator>
      <pubDate>Sat, 20 Mar 2021 03:00:06 +0000</pubDate>
      <link>https://dev.to/anirban99/build-rest-api-with-spring-boot-and-kotlin-4ii9</link>
      <guid>https://dev.to/anirban99/build-rest-api-with-spring-boot-and-kotlin-4ii9</guid>
      <description>&lt;h2&gt;
  
  
  1. Overview
&lt;/h2&gt;

&lt;p&gt;In this article, we're going to build a REST API using Spring Boot 2.x and Kotlin. Meanwhile, dedicated support for Kotlin was introduced since Spring Framework 5.0. We can read about the supported features in the official &lt;a href="https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Versions"&gt;Spring Framework documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In particular, the application will expose data via a REST API and persist data in an embedded H2 database.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Use Case
&lt;/h2&gt;

&lt;p&gt;We'll build Restful APIs for an employee information application. &lt;strong&gt;A user can create, retrieve, update and delete an employee using this application&lt;/strong&gt;. An employee has an id, username, first name, last name, email id, and date of birth. Moreover, the username of an employee must be unique.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;We'll use an embedded H2 database as our data source along with JPA and Hibernate to access the data from the database&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Setup
&lt;/h2&gt;

&lt;p&gt;We can use the Spring Initializer tool to create a Spring Boot application. Besides, we can read about the other ways that we can create a Spring Boot project in the &lt;a href="https://theanirban.dev/how-to-create-a-spring-boot-project/"&gt;blog post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Subsequently, we will add Spring Web, Spring Data JPA, H2 Database, Spring Boot Devtools as the dependencies&lt;/strong&gt;. So now we have all the basic dependencies in the &lt;code&gt;build.gradle.kts&lt;/code&gt; that will allow us to work with Spring Boot and Kotlin:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The Gradle build file also contains some essential plugins:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;kotlin-spring&lt;/code&gt; compiler plugin is a wrapper on top of the &lt;code&gt;all-open&lt;/code&gt; plugin. &lt;strong&gt;The &lt;code&gt;all-open&lt;/code&gt; compiler plugin ensures that the Kotlin classes are annotated and their members are &lt;code&gt;open&lt;/code&gt;.&lt;/strong&gt; This makes it convenient to use libraries such as Spring AOP that require classes to be open unlike Kotlin classes and their members which are final by default.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;kotlin-jpa&lt;/code&gt; compiler plugin is a wrapper on top of the &lt;code&gt;no-arg&lt;/code&gt; plugin. &lt;strong&gt;The &lt;code&gt;no-arg&lt;/code&gt; compiler plugin generates a no-argument constructor for classes annotated with &lt;code&gt;Entity&lt;/code&gt;, &lt;code&gt;MappedSuperclass&lt;/code&gt;, and &lt;code&gt;Embeddable&lt;/code&gt;.&lt;/strong&gt; This ensures that JPA (Java Persistence API) can instantiate the class since it expects a no-argument constructor defined for its entities.&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  3.1. Configure Database
&lt;/h3&gt;

&lt;p&gt;We have to configure the H2 database properties so that Spring Boot can create a data source. To define such properties, we can use an external configuration. &lt;strong&gt;Furthermore, we can define such external configuration using properties files, YAML files, environment variables, and command-line arguments&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In general, Spring Boot provides the &lt;code&gt;application.properties&lt;/code&gt; file to define such database properties by default&lt;/strong&gt;. The properties file uses a key-value format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Alternatively, we can use YAML-based configuration files which use hierarchical data&lt;/strong&gt;. The YAML files significantly help to avoid repeated prefixes and make is more readable compared to the properties file:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We can also use the &lt;code&gt;application.yml&lt;/code&gt; file to define hibernate properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We set the &lt;code&gt;ddl-auto&lt;/code&gt; property to &lt;code&gt;update&lt;/code&gt;. It will update the database schema based on the modifications in the domain model in our application.
This default value is &lt;code&gt;create-drop&lt;/code&gt; if we use an embedded database without any schema manager.
&lt;strong&gt;In case we're using a schema manager such as Liquibase or Flyway, we should consider using &lt;code&gt;validate&lt;/code&gt;.&lt;/strong&gt; It tries to validate the database schema according to the entities that we have created in the application and throws an error if the schema doesn’t match the entity specifications.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;show-sql&lt;/code&gt; property enables logging of SQL statement.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;generate-ddl&lt;/code&gt; property ensures whether to initialize the schema on startup.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;dialect&lt;/code&gt; property ensures that Hibernate generates better SQL for the chosen database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Domain Model - Kotlin Data class
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The domain model is the core part of the application&lt;/strong&gt;. We can create a domain model &lt;code&gt;Employee&lt;/code&gt; using a data class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In addition, a &lt;code&gt;data class&lt;/code&gt; in Kotlin automatically generates &lt;code&gt;equals/hashCode&lt;/code&gt; pair, &lt;code&gt;toString&lt;/code&gt;, and &lt;code&gt;copy&lt;/code&gt; functions.&lt;/strong&gt; Besides, We don't need to define getter and setter methods like Java:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;@Entity&lt;/code&gt; annotation specifies that the class is an entity and mapped to a database table.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@Table&lt;/code&gt; annotation specifies the name of the database table that is used for mapping.
&lt;strong&gt;If we use the &lt;code&gt;@Table&lt;/code&gt; annotation without a table name, then Spring generates the table name from the class name&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@Id&lt;/code&gt; annotation specifies the property which is the primary key in the entity class.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@GeneratedValue&lt;/code&gt; annotation specifies the generation strategies for the values of the primary keys.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@Column&lt;/code&gt; annotation specifies the mapped column for a persistent property. If we do not use the &lt;code&gt;@Column&lt;/code&gt; annotation, then Spring generates the column name from the property name.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Repository
&lt;/h2&gt;

&lt;p&gt;We're going to create a repository interface to interact with the database. &lt;strong&gt;Moreover, the &lt;code&gt;EmployeeRepository&lt;/code&gt; interface will extend from the &lt;code&gt;JpaRepository&lt;/code&gt; interface&lt;/strong&gt;. This ensures that all the CRUD methods on the &lt;code&gt;Employee&lt;/code&gt; entity are available:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;@Repository&lt;/code&gt; annotation specifies that the class is a repository and represents the data access layer in our application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Service
&lt;/h2&gt;

&lt;p&gt;Now, we're going to create a service class that will provide the business logic. &lt;strong&gt;Besides, the service layer can interact with the data access layer using JPA&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We inject an instance of the &lt;code&gt;EmployeeRepository&lt;/code&gt; via constructor in &lt;code&gt;EmployeeService&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;@Service&lt;/code&gt; annotation specifies that the class is a service.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;getAllEmployees()&lt;/code&gt; function can fetch a list of all employees.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;getEmployeesById()&lt;/code&gt; function can fetch one employee based on the id. We provide the employee id as a parameter to the function.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;createEmployee()&lt;/code&gt; function can create a new employee. We provide the required properties of the new employee as a parameter to the function.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;updateEmployeeById()&lt;/code&gt; function can update the employee details based on the id. We provide both the employee id and the properties as parameters to the function.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;deleteEmployeesById()&lt;/code&gt; function can delete an employee based on the id. We provide the employee id as a parameter to the function.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  7. Controller
&lt;/h2&gt;

&lt;p&gt;We implement the APIs for all the CRUD operations in the controller layer which invokes the underlying service.&lt;/p&gt;

&lt;p&gt;We define a &lt;code&gt;EmployeeController&lt;/code&gt; as our controller class. &lt;strong&gt;In particular, it's a REST controller that provides endpoints for creating, manipulating, and deleting employees&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;EmployeeService&lt;/code&gt; class is wired into the controller to return the values. Also, we reuse the entities as data transfer object for simplicity:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The &lt;code&gt;@RestController&lt;/code&gt; annotation specifies that the class is a controller and capable of handling requests. It combines both the &lt;code&gt;@Controller&lt;/code&gt; and &lt;code&gt;@ResponseBody&lt;/code&gt; annotations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Spring provides several annotations to handle the different incoming HTTP requests like GET, POST, PUT and DELETE&lt;/strong&gt;. These annotations are &lt;code&gt;@GetMapping&lt;/code&gt;,&lt;code&gt;@PostMapping&lt;/code&gt;,&lt;code&gt;@PutMapping&lt;/code&gt;, and &lt;code&gt;@DeleteMapping&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  8. Running the application
&lt;/h2&gt;

&lt;p&gt;We can run the application using the following command in the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;gradle bootRun
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The Spring Boot application will start running at &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  9. Exploring the APIs
&lt;/h2&gt;
&lt;h3&gt;
  
  
  9.1. Create an Employee
&lt;/h3&gt;

&lt;p&gt;We send the following request to create an employee:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;We receive the following response in JSON format:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  9.2. Get All Employees
&lt;/h3&gt;

&lt;p&gt;We send the following request to fetch all employees:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We receive the following response in JSON format:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  9.3. Get an Employee
&lt;/h3&gt;

&lt;p&gt;We send the following request to fetch an employee based on the employee id:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We receive the following response in JSON format:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  9.4. Update an Employee
&lt;/h3&gt;

&lt;p&gt;We send the following request to update employee properties based on the employee id:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We receive the following response in JSON format:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  9.5. Delete an Employee
&lt;/h3&gt;

&lt;p&gt;We send the following request to delete an employee based on the employee id:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  10. Conclusion
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we looked into creating a microservice application and expose REST API using Kotlin and Spring Boot. In the process, I have also used some best practices which we can utilize while building such applications.&lt;/p&gt;

&lt;p&gt;The code for these examples is available on &lt;a href="https://github.com/anirban99/spring-boot-examples/tree/main/spring-boot-boilerplate"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To learn more, check out the &lt;a href="https://theanirban.dev/categories/spring-boot"&gt;related articles&lt;/a&gt; on Spring Boot.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://theanirban.dev/"&gt;Anirban's Tech Blog&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>spring</category>
      <category>springboot</category>
      <category>rest</category>
    </item>
    <item>
      <title>How To Create a Spring Boot Project</title>
      <dc:creator>Anirban</dc:creator>
      <pubDate>Fri, 12 Feb 2021 03:00:06 +0000</pubDate>
      <link>https://dev.to/anirban99/how-to-create-a-spring-boot-project-58ha</link>
      <guid>https://dev.to/anirban99/how-to-create-a-spring-boot-project-58ha</guid>
      <description>&lt;h2&gt;
  
  
  1. Overview
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we'll look into the different ways we can create a Spring Boot project.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Using Spring Initializer in spring.io
&lt;/h2&gt;

&lt;p&gt;We can create a Spring Boot project by using the Spring Initializer in &lt;a href="http://start.spring.io"&gt;start.spring.io&lt;/a&gt;. &lt;strong&gt;This is the quickest way to create an application in Spring Boot which is one of the most popular frameworks for creating web applications&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The Spring Initializer offers different options for choosing the build tools, programming languages, Spring Boot versions, and the related dependencies.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Aka8Kbm6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505502683/l-N9Vlhmd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Aka8Kbm6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505502683/l-N9Vlhmd.png" alt="springio.png" width="880" height="544"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2.1. Build Tools
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;We have the option to choose between Maven and Gradle as our build tool&lt;/strong&gt;. In this case, we'll choose Gradle as our build tool for the Spring Boot application.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.2. Language
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Spring Initializer supports multiple JVM languages like Java, Kotlin, and Groovy to build a web application&lt;/strong&gt;. In this case, we'll choose Kotlin as our programming language.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.3. Version
&lt;/h3&gt;

&lt;p&gt;We should always aim to choose the latest stable Spring Boot version for building our application. &lt;strong&gt;The SNAPSHOT versions are not stable and should be avoided. The versions labeled with M signifies Milestone versions&lt;/strong&gt;. It refers to a future stable version.&lt;/p&gt;

&lt;p&gt;In this case, the latest stable version is 2.4.2 while M1 is supposed to have version 2.5.0 (M1). So, version 2.5.0 (M1) is the future stable release version.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.4. Project Metadata
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;We can also define the project metadata which includes the group, artifact, name, description, package name, packaging, and Java version&lt;/strong&gt;. In this case, we'll choose Jar as the packaging option. The Java version will be 11.&lt;/p&gt;

&lt;h3&gt;
  
  
  2.5. Dependencies
&lt;/h3&gt;

&lt;p&gt;Finally, we have to define the dependencies by selecting the &lt;strong&gt;&lt;em&gt;Add Dependency&lt;/em&gt;&lt;/strong&gt; button. &lt;strong&gt;In this case, we can add a Spring Web dependency which should be sufficient to build a simple RESTful web application&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We can select the Generate button and download the ZIP archive locally. After that, we can extract the project and import it into an IDE like IntelliJ IDEA, Spring Tools, Eclipse, etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Using Spring Initializer in IntelliJ IDEA
&lt;/h2&gt;

&lt;p&gt;We can create a Spring Boot project by using the Spring Initializer plugin in IntelliJ IDEA.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.1. Create a New Project
&lt;/h3&gt;

&lt;p&gt;Firstly, we select the option Create New Project.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3AbD9D2g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505520635/CCfIZdKKa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3AbD9D2g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505520635/CCfIZdKKa.png" alt="intellij1.png" width="880" height="847"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2. Use Spring Initializer
&lt;/h3&gt;

&lt;p&gt;After that, we select the Spring Initializer to generate a Spring Boot application. Then we have to download or assign a project SDK and select Next.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rgs5gsEg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505539512/87JwuogN6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rgs5gsEg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505539512/87JwuogN6.png" alt="intellij2.png" width="880" height="957"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3.3. Configure Project Settings
&lt;/h3&gt;

&lt;p&gt;Now we'll configure the project settings as per our requirements. &lt;strong&gt;In this case, we choose Gradle as the build tool, Kotlin as the programming language, Jar as the packaging option, and Java version 11&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Select Next to continue.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vCOxjBSm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505555294/5I56DUZmq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vCOxjBSm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505555294/5I56DUZmq.png" alt="intellij3.png" width="880" height="958"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3.4. Select Dependencies
&lt;/h3&gt;

&lt;p&gt;Also, we need to define the external dependencies of our Spring Boot application. &lt;strong&gt;We can choose Spring Web dependency which should be sufficient to build a simple RESTful web application&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Select Next to continue.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RwZa_Cf8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505569390/vrP42FI1k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RwZa_Cf8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505569390/vrP42FI1k.png" alt="intellij4.png" width="880" height="958"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3.5. Project Name and Location
&lt;/h3&gt;

&lt;p&gt;Finally, we can define a name for the Spring Boot project and the directory in the local machine. In this case, we continue with the default values.&lt;/p&gt;

&lt;p&gt;Select Finish and the Spring Boot project is created.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--E24BWXdK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505581083/3vvixxp93.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--E24BWXdK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1615505581083/3vvixxp93.png" alt="intellij5.png" width="880" height="958"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Conclusion
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we discussed the different ways to create a Spring Boot project.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://theanirban.dev/"&gt;Anirban's Tech Blog&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>java</category>
      <category>kotlin</category>
      <category>microservices</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Null Safety in Kotlin</title>
      <dc:creator>Anirban</dc:creator>
      <pubDate>Tue, 30 Jun 2020 03:00:06 +0000</pubDate>
      <link>https://dev.to/anirban99/null-safety-in-kotlin-eoe</link>
      <guid>https://dev.to/anirban99/null-safety-in-kotlin-eoe</guid>
      <description>&lt;h2&gt;
  
  
  1. Overview
&lt;/h2&gt;

&lt;p&gt;In this article, we’ll look into the handling of null references in Kotlin.&lt;/p&gt;

&lt;p&gt;Any programming language which has the concept of null reference throws a &lt;strong&gt;&lt;em&gt;NullPointerException&lt;/em&gt;&lt;/strong&gt;. It has been referred to as a &lt;strong&gt;&lt;em&gt;billion-dollar mistake&lt;/em&gt;&lt;/strong&gt;. &lt;a href="https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions"&gt;Wiki&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Nullable and Non-Nullable Type
&lt;/h2&gt;

&lt;p&gt;Kotlin aims at eliminating the risk of &lt;strong&gt;&lt;em&gt;NullPointerException&lt;/em&gt;&lt;/strong&gt;. It distinguishes between nullable and non-nullable references as a part of its type system. &lt;strong&gt;In Kotlin, all variables are non-nullable by default&lt;/strong&gt;. So, we cannot assign a null value to a variable because it’ll throw a compilation error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var country: String = "India"
country = null //compilation error

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To define a nullable variable, we must append a question mark(?) to the type declaration:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var city: String? = "Kolkata"
city = null

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

&lt;/div&gt;



&lt;p&gt;We can call a method or access a property on a non-nullable variable. However, in the case of nullable variables, we need to handle the null case explicitly. Otherwise, it will throw a compilation error since Kotlin knows that the variable contains null references:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val a : String = country.length
val b : String = city.length //compilation error

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

&lt;/div&gt;



&lt;p&gt;Let’s look at the different ways how we can handle null references safely in Kotlin.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Working With Nullable Types
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1. Null Check
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;We can use the if-else expression to explicitly check for nullable variables&lt;/strong&gt;. However, this option works only where the variable is immutable. Depending on the complexity of the conditions, this can also lead to nested expressions.&lt;/p&gt;

&lt;p&gt;Let’s look at an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val city: String? = "Kolkata"
return if (city != null) {
    city.length
} else {
    null
}

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2. Safe Call Operator (?.)
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Kotlin has a safe call operator (?.) to handle null references&lt;/strong&gt;. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.&lt;/p&gt;

&lt;p&gt;Let’s see how to use a &lt;strong&gt;&lt;em&gt;safe call operator&lt;/em&gt;&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: String? = "India"
assertEquals(5, country?.length)
val city: String? = null

assertNull(city?.length)

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In addition, we can also use the safe call operator for multiple chain calls&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: Country? = Country(City("Kolkata", "003"))
val code: String? = country?.city?.code
assertEquals("003", code)

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

&lt;/div&gt;



&lt;p&gt;However, the chain calls return null if any of the properties are null:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: Country? = Country(null)
val code: String? = country?.city?.code

assertNull(code)

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.3. Using let() Method
&lt;/h3&gt;

&lt;p&gt;We can use the &lt;strong&gt;&lt;em&gt;let()&lt;/em&gt;&lt;/strong&gt; method along with the safe call operator to act on a non-nullable variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val cities: List&amp;lt;String?&amp;gt; = listOf("Kolkata", null, "Mumbai")
var name: List&amp;lt;String?&amp;gt; = emptyList()
for (city in cities) {
    city?.let { name = name.plus(it) }
}
return name

assertEquals(2, name.size)

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.4. Using also() Method
&lt;/h3&gt;

&lt;p&gt;We can use the also() method to execute additional operations like logging and printing of the non-nullable variables. &lt;strong&gt;Furthermore, this method can be used in a chain with let() or run() method&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Here's how we can use &lt;strong&gt;&lt;em&gt;also()&lt;/em&gt;&lt;/strong&gt; method along with &lt;strong&gt;&lt;em&gt;let()&lt;/em&gt;&lt;/strong&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val cities: List&amp;lt;String?&amp;gt; = listOf("Kolkata", null, "Mumbai")
var name: List&amp;lt;String?&amp;gt; = emptyList()
for (city in cities) {
    city?.let {
        name = name.plus(it)
        it
    }?.also { println("Logging the value: $it") }
}
return name

assertEquals(2, name.size)

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.5. Using run() Method
&lt;/h3&gt;

&lt;p&gt;We can use the &lt;strong&gt;&lt;em&gt;run()&lt;/em&gt;&lt;/strong&gt; method to execute some operations on a non-nullable reference. &lt;strong&gt;This method operates using this reference and returns the value of the lambda result&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val countries: List&amp;lt;String?&amp;gt; = listOf("India", null, "Germany")
var name: List&amp;lt;String?&amp;gt; = emptyList()
for (country in countries) {
    country?.run {
        name = name.plus(this)
        this
    }?.also { println("Logging the value: $it") }
}
return name

assertEquals(2, name.size)

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.6. Elvis Operator (?:)
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;We can use the Elvis operator (?:) to return a default value only if the original variable has a null value&lt;/strong&gt;. If the left-side expression of the Elvis operator has a non-nullable value, then it is returned. Otherwise, the right-side expression is returned.&lt;/p&gt;

&lt;p&gt;Let’s take a look at how the &lt;strong&gt;&lt;em&gt;Elvis operator&lt;/em&gt;&lt;/strong&gt; works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: Country? = Country(City("New Delhi", null))
val result = country?.city?.code ?: "Not available"

assertEquals("Not available", result)

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;We can use the Elvis operator with a safe call operator to invoke a method or property of the variable&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: Country? = Country(City("Mumbai", "002"))
val result = country?.city?.code ?: "Not available"

assertEquals("002", result)

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;We can also use throw and return expression in the right-side expression of the Elvis operator&lt;/strong&gt;. So instead of default values, we can throw specific exceptions in the right-side expressions of the Elvis operator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: Country? = Country(City("Chennai", null))
val result = country?.city?.code ?: throw IllegalArgumentException("Not a valid code")

assertThrows&amp;lt;IllegalArgumentException&amp;gt; { result }

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.7. Not Null Assertion Operator (!!)
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;We can use the not-null assertion operator (!!) to explicitly throw a NullPointerException&lt;/strong&gt;. This operator converts any reference to its non-nullable type and throws an exception if the reference has a null value. Let’s have a look into how we can throw &lt;strong&gt;&lt;em&gt;NullPointerException&lt;/em&gt;&lt;/strong&gt; using &lt;strong&gt;&lt;em&gt;not-null assertion operator(!!)&lt;/em&gt;&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: String? = null
val result : Int = country!!.length
assertThrows&amp;lt;NullPointerException&amp;gt; { result }

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

&lt;/div&gt;



&lt;p&gt;However, if the reference has a non-nullable value, then it is executed successfully:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val country: String? = "India"
val result : Int = country!!.length
assertEquals(5, result)

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The not-null assertion operator should be used carefully since it’s a potential sign of a NullPointerException&lt;/strong&gt;. We should avoid using &lt;strong&gt;&lt;em&gt;multiple non-null assertions&lt;/em&gt;&lt;/strong&gt; like the following since it makes it harder to debug which property is null:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;country!!.city!!.code

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

&lt;/div&gt;



&lt;p&gt;Additionally, &lt;strong&gt;We should always try to use safe call operator in such cases to ensure NullPointerException doesn’t occur&lt;/strong&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;country?.city?.code

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Nullability in Collections
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Kotlin collections are non-nullable by default&lt;/strong&gt;. So, in order to define a collection of nullable types in Kotlin, we have to append the question mark (?) to the type declaration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val countries: List&amp;lt;String?&amp;gt; = listOf("India", null, "Germany", "Russia", null)

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

&lt;/div&gt;



&lt;p&gt;We can use the following way to define a nullable collection in Kotlin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var countries: List&amp;lt;String&amp;gt;? = listOf("India", "Germany", "Russia")
countries = null

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.1. Filtering Nullable Types
&lt;/h3&gt;

&lt;p&gt;We can filter a list that contains nullable values to return only the non-nullable values using the &lt;strong&gt;&lt;em&gt;filterNotNull()&lt;/em&gt;&lt;/strong&gt; method. Let’s have a look at an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val countries: List&amp;lt;String?&amp;gt; = listOf("India", null, "Germany", "Russia", null)
val result: List&amp;lt;String&amp;gt; = countries.filterNotNull()
assertEquals(3, result.size)
assertEquals("Russia", result[2])

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we look into the various ways to handle nullable references in Kotlin.&lt;/p&gt;

&lt;p&gt;The code for these examples is available on &lt;a href="https://github.com/anirban99/kotlin-examples"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://theanirban.dev/"&gt;Anirban's Tech Blog&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>functional</category>
      <category>softwareengineering</category>
      <category>programming</category>
    </item>
    <item>
      <title>Hexagonal Architecture in Java</title>
      <dc:creator>Anirban</dc:creator>
      <pubDate>Sat, 23 May 2020 03:00:06 +0000</pubDate>
      <link>https://dev.to/anirban99/hexagonal-architecture-in-java-5c2o</link>
      <guid>https://dev.to/anirban99/hexagonal-architecture-in-java-5c2o</guid>
      <description>&lt;h2&gt;
  
  
  1. Overview
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we'll take a look into the &lt;strong&gt;hexagonal architecture in Java&lt;/strong&gt;. To illustrate this further, we'll create a Spring Boot application.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Hexagonal Architecture
&lt;/h2&gt;

&lt;p&gt;The hexagonal architecture describes a pattern for designing software applications around the domain logic. &lt;strong&gt;The hexagon describes the core of the application consisting of the domain object and the use cases of the application&lt;/strong&gt;. &lt;strong&gt;The edges of the hexagon provide the inbound and outbound ports to the outside parts of the hexagon&lt;/strong&gt; such as web interface, databases, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So, in this kind of software architecture, all the dependencies between the components point towards the domain object&lt;/strong&gt;. &lt;strong&gt;Therefore, the communication between the core application and the outside part is only possible using ports and adapters&lt;/strong&gt;. In the following sections, we can have a deep dive into the different layers of hexagonal architecture.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Domain Object
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The domain object is the core part of the application&lt;/strong&gt;. It can have both state and behaviour. However, it doesn’t have any outward dependency. So any change in the other layers has no impact on the domain object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The domain object changes only if there is a change in the business requirement&lt;/strong&gt;. Hence, this is an example of the Single Responsibility Principle among the SOLID principles of software design.&lt;/p&gt;

&lt;p&gt;First, let’s create a domain object &lt;strong&gt;&lt;em&gt;Product&lt;/em&gt;&lt;/strong&gt; that forms the core of the application. It contains product-related information and business validations:&lt;br&gt;
&lt;/p&gt;

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

    private Integer productId;
    private String type;
    private String description;

    public Product() {
        super();
    }

    public Product(Integer productId, String type, String description) {
        this.productId = productId;
        this.type = type;
        this.description = description;
    }

    //getters
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Ports
&lt;/h2&gt;

&lt;p&gt;The ports are interfaces that allow inbound and outbound flow. Therefore, the core part of the application communicates with the outside part using the dedicated ports.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.1. Inbound Port
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The inbound port exposes the core application to the outside&lt;/strong&gt;. It is an interface that can be called by the outside components. &lt;strong&gt;These outside components calling an inbound port are called primary or input adapters&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let's define a &lt;strong&gt;&lt;em&gt;ProductService&lt;/em&gt;&lt;/strong&gt; interface which is the inbound port:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ProductService {

    List&amp;lt;Product&amp;gt; getProducts();

    Product getProductById(Integer productId);

    Product addProduct(Product product);

    Product removeProduct(Integer productId);
}

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2. Outbound Port
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The outbound port allows outside functionality to the core application&lt;/strong&gt;. It is an interface that enables the use case of the core application to communicate with the outside such as database access. &lt;strong&gt;Hence, the outbound port is implemented by the outside components which are called secondary or output adapters&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let's define a &lt;strong&gt;&lt;em&gt;ProductRepository&lt;/em&gt;&lt;/strong&gt; interface which is an outbound port:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ProductRepository {

    List&amp;lt;Product&amp;gt; getProducts();

    Product getProductById(Integer productId);

    Product addProduct(Product product);

    Product removeProduct(Integer productId);
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Adapters
&lt;/h2&gt;

&lt;p&gt;The adapters are the outside part of the hexagonal architecture. So, they interact with the core application only by using the inbound and outbound ports.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.1. Primary Adapters
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The Primary adapters are also known as input or driving adapters. Therefore, they drive the application by invoking the corresponding use case of the core application using the inbound ports&lt;/strong&gt;. For example, primary adapters are REST APIs or web interfaces.&lt;/p&gt;

&lt;p&gt;Let's define a &lt;strong&gt;&lt;em&gt;ProductController&lt;/em&gt;&lt;/strong&gt; class as our primary adapter. In particular, it's a REST controller that provides endpoints for creating and accessing products. Subsequently, it uses the inbound port service to interact with the core application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@RestController
@RequestMapping("/api/v1/product")
public class ProductController {

    private ProductService productService;

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public ResponseEntity&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt; getProducts() {
        return new ResponseEntity&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt;(productService.getProducts(), HttpStatus.OK);
    }

    @GetMapping("/{productId}")
    public ResponseEntity&amp;lt;Product&amp;gt; getProductById(@PathVariable Integer productId) {
        return new ResponseEntity&amp;lt;Product&amp;gt;(productService.getProductById(productId), HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity&amp;lt;Product&amp;gt; addProduct(@RequestBody Product product) {
        return new ResponseEntity&amp;lt;Product&amp;gt;(productService.addProduct(product), HttpStatus.OK);
    }

    @DeleteMapping("/{productId}")
    public ResponseEntity&amp;lt;Product&amp;gt; removeProduct(@PathVariable Integer productId) {
        return new ResponseEntity&amp;lt;Product&amp;gt;(productService.removeProduct(productId), HttpStatus.OK);
    }
}

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2. Secondary Adapters
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The Secondary adapters are also known as output or driven adapters. These are implementations of the outbound port interface&lt;/strong&gt;. The use case of the core application invokes the secondary adapters using the output port. For instance, secondary adapters are connections to the database and external API calls.&lt;/p&gt;

&lt;p&gt;Let's define a &lt;strong&gt;&lt;em&gt;ProductRepositoryImplementation&lt;/em&gt;&lt;/strong&gt; class as our secondary adapter. In particular, this class implements the outbound port interface &lt;strong&gt;&lt;em&gt;ProductRepository&lt;/em&gt;&lt;/strong&gt; and allows the core application to access 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;@Repository
public class ProductRepositoryImplementation implements ProductRepository {

    private static final Map&amp;lt;Integer, Product&amp;gt; productMap = new HashMap&amp;lt;Integer, Product&amp;gt;(0);

    @Override
    public List&amp;lt;Product&amp;gt; getProducts() {
        return new ArrayList&amp;lt;Product&amp;gt;(productMap.values());
    }

    @Override
    public Product getProductById(Integer productId) {
        return productMap.get(productId);
    }

    @Override
    public Product addProduct(Product product) {
        productMap.put(product.getProductId(), product);
        return product;
    }

    @Override
    public Product removeProduct(Integer productId) {
        if(productMap.get(productId)!= null){
            Product product = productMap.get(productId);
            productMap.remove(productId);
            return product;
        } else
            return null;

    }
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The adapters provide flexibility to the application without influencing the core application logic&lt;/strong&gt;. If the application can be used by a new client in addition to the existing one, we can add the new client to the inbound port.&lt;/p&gt;

&lt;p&gt;In addition, if the application requires a different database, we can add a new secondary adapter implementing the same outbound port.&lt;/p&gt;

&lt;h2&gt;
  
  
  6. Use cases of the core application
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The use cases of the core application are the inside part of the hexagonal architecture&lt;/strong&gt;. They are specific use case implementations of the inbound port. &lt;strong&gt;Hence, it contains all the use case-specific business rule validations and logic&lt;/strong&gt;. The use case has no outside dependency similar to the domain objects.&lt;/p&gt;

&lt;p&gt;Let's define a &lt;strong&gt;&lt;em&gt;ProductServiceImplementation&lt;/em&gt;&lt;/strong&gt; class that provides the specific use case implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class ProductServiceImplementation implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List&amp;lt;Product&amp;gt; getProducts() {
        return productRepository.getProducts();
    }

    @Override
    public Product getProductById(Integer productId) {
        return productRepository.getProductById(productId);
    }

    @Override
    public Product addProduct(Product product) {
        return productRepository.addProduct(product);
    }

    @Override
    public Product removeProduct(Integer productId) {
        return productRepository.removeProduct(productId);
    }
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Conclusion
&lt;/h2&gt;

&lt;p&gt;The hexagonal architecture offers several benefits compared to a layered architecture:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It &lt;strong&gt;simplifies the architecture design&lt;/strong&gt; by separating the inside and outside parts of the application&lt;/li&gt;
&lt;li&gt;The core business logic is isolated from any external dependencies which help to &lt;strong&gt;achieve a high degree of decoupling&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;ports allow flexibility in connecting to new adapters&lt;/strong&gt; in the form of new web clients or databases&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The hexagonal architecture might be an overhead for designing simple CRUD applications. However, this architecture is &lt;strong&gt;useful when we are designing a domain-driven application&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The code for these examples is available over on &lt;a href="https://github.com/anirban99/hexagonal-architecture"&gt;Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://theanirban.dev"&gt;Anirban's Tech Blog&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

</description>
      <category>java</category>
      <category>kotlin</category>
      <category>springboot</category>
      <category>microservices</category>
    </item>
  </channel>
</rss>
