<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Augustine Alul - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Augustine Alul - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 22:23:57 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/augustinealul/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Data Transfer Objects? Learn to Use DTOs in Your Java Spring-Based Projects ]]>
                </title>
                <description>
                    <![CDATA[ High performance and privacy are at the heart of most successful software systems. No one wants to use a software service that takes a ridiculous amount of time to load – and no company wants their users’ data exposed at the slightest vulnerability. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-dtos-java/</link>
                <guid isPermaLink="false">68a4ba42388ce2383306b9b3</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Springboot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dto ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Augustine Alul ]]>
                </dc:creator>
                <pubDate>Tue, 19 Aug 2025 17:54:10 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755626027353/feb7f6b6-4841-4559-a976-e73c708c7153.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>High performance and privacy are at the heart of most successful software systems. No one wants to use a software service that takes a ridiculous amount of time to load – and no company wants their users’ data exposed at the slightest vulnerability. This is why DTOs are a crucial topic for software engineers to understand.</p>
<p>Using DTOs is helpful when building applications that hold sensitive data like financial or health records. When used properly, DTOs can prevent sensitive fields from being exposed to the client side. In critical systems, they can further tighten security and reduce failure conditions by ensuring that only valid and required fields are accepted.</p>
<p>In this article, you’ll learn what DTOs are, why they’re important, and the best ways to create them for your Spring-based applications.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This is a slightly more advanced tutorial. So to understand it better, you should have a sound knowledge of Java concepts like objects, getters and setters, and Spring/Spring Boot. You should also have a solid understanding of how software works in general.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-dto">What is a DTO?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-dto-for-a-spring-based-application">How to Create a DTO for a Spring-Based Application</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-dtos-from-two-or-multiple-objects">How to Create DTOs From Two or Multiple Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-dto">What is a DTO?</h2>
<p>DTOs stand for Data Transfer Objects. It is a software design pattern that ensures the transfer of tailored/streamlined data objects between different layers of a software system. </p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfY0uhU1igdbtYzBocBZFOY37O2IjXOD5wCJ26DS0B3U6SZnIswn1n8kWi7ZKL5tQfSQjAZR7ecJ-5Aavop5iB3meJA5ywuKlv7fChG2Oq1_fxNtNW_8RijTFQx2d1ZG-A5y5uYag?key=3uLKQHZqj2e_zuUsBBBZwg" alt="Image showing the lifecycle of DTO in a software system" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Image <a target="_blank" href="https://www.linkedin.com/pulse/clean-spring-boot-apis-separating-entities-dtos-mappers-fabio-ribeiro-zrn9f?utm_source=share&amp;utm_medium=member_ios&amp;utm_campaign=share_via">source</a> | Fabio Ribeiro</p>
<p>The direction of data transfer with DTOs across the various layers of software is bi-directional. DTOs are either used to carry data in an inbound direction from an external client/user to the software or are constructed and used to carry data in an outbound direction from the software.</p>
<p>DTOs only hold field data, constructors, and necessary getter and setter methods. So they are Plain Old Java Objects (POJOs).</p>
<p>You can see the bi-directional flow in the image below:</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdHient8hAwmq3b3KhZi2tNuh0n_1ZuIFJxef1VnM_R5K4KoC0gjeZAF1vZ1d1_lliWKmltiNhhtlfCpadydurab8dNkfLQiru1wGcl2Egak-_3-IYI_n5adrbcrU-4ezKIVERU?key=3uLKQHZqj2e_zuUsBBBZwg" alt="Image showing the bi-directional flow of DTO in a software system, flowing from controller to Database and from Database back to the controller" width="600" height="400" loading="lazy"></p>
<p>Image <a target="_blank" href="https://www.linkedin.com/pulse/clean-spring-boot-apis-separating-entities-dtos-mappers-fabio-ribeiro-zrn9f?utm_source=share&amp;utm_medium=member_ios&amp;utm_campaign=share_via">source</a> | Fabio Ribeiro</p>
<h3 id="heading-why-use-dtos">Why Use DTOs?</h3>
<h4 id="heading-1-data-privacy">1. Data Privacy</h4>
<p>In Spring Boot, entities serve as the blueprint for creating data objects. These entities are classes annotated with <code>@Entity</code> and map to a database table. An instance of the entity class represents a database row or record, while a field in the entity class represents a database column. </p>
<p>When registering for a software service or product, the user might be asked to provide both sensitive and non-sensitive data for the proper functioning of the application. These data are held as fields by the entity class and finally mapped and persisted to the database. </p>
<p>When we need to retrieve data from the database and expose it through an API endpoint based on the query provided – say, a query to retrieve a user record or entity, Jackson (the serializer dependency commonly used in Spring-based applications) serialises all the data fields contained in the retrieved user entity. Now, imagine you have a User entity that contains fields like password, credit card details, date of birth, home address, and other sensitive data you wouldn’t want to reveal when the User entity is being serialised. Well, this is where DTOs come in. </p>
<p>With DTOs, you can retrieve the complete entity (containing both sensitive and insensitive data) from the database, create a custom class (say <code>UserDTO.java</code>) that only holds the insensitive fields that you feel are safe to expose, and finally, map the database-retrieved entity to the safe-to-expose UserDTO object. This way, the UserDTO is what gets serialised and exposed through the API endpoint and not the complete entity – keeping the sensitive data confidential.</p>
<h4 id="heading-2-improved-software-performance">2. Improved Software Performance</h4>
<p>DTOs can improve the performance of your software application by reducing the number of API calls for data retrieval. With DTOs, you can return serialized data from more than one entity in just one API call.</p>
<p>Let’s say that in your Spring Boot application, there are User and Follower entities, and you want to return user data as well as their followers. Typically, Jackson can only serialize one entity at a time, either User or Follower. But with a DTO, you can combine these two entities into one and eventually serialize and return all the data in a single request, instead of building two endpoints to return user and follower data.</p>
<p>In the next section, I’ll show you the various ways you can create DTOs for your Spring Boot project with code implementations.</p>
<h2 id="heading-how-to-create-a-dto-for-a-spring-based-application">How to Create a DTO for a Spring-Based Application</h2>
<p>There are two main approaches to creating DTOs in Spring/Spring Boot:</p>
<h3 id="heading-1-creating-custom-objects-and-handling-mapping-manually">1. Creating Custom Objects and Handling Mapping Manually</h3>
<p>This approach requires you to handle the mapping/transforming of your existing entity to the custom object (DTO) by yourself – that is to say, you write the code that creates the DTO and sets the DTO fields to the values present in the existing entity. This is common for developers who prefer fine-grained control, but it can be tedious for large-scale projects. </p>
<p>Follow the steps below to create a UserDTO from a User entity:</p>
<h4 id="heading-step-1-create-the-dto-class">Step 1: Create the DTO class</h4>
<p>Create a new file named <strong>UserDTO.java</strong> and write the code below into it:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserDTO</span> </span>{
    <span class="hljs-keyword">private</span> Long id;
    <span class="hljs-keyword">private</span> String firstName;
    <span class="hljs-keyword">private</span> String lastName;
    <span class="hljs-keyword">private</span> String email;


    <span class="hljs-comment">// No-args Constructor</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserDTO</span><span class="hljs-params">()</span> </span>{}

    <span class="hljs-comment">// All-args constructor</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserDTO</span><span class="hljs-params">(Long id, String firstName, String lastName, String email)</span> </span>{
        <span class="hljs-keyword">this</span>.id = id;
        <span class="hljs-keyword">this</span>.firstName = firstName;
        <span class="hljs-keyword">this</span>.lastName = lastName;
        <span class="hljs-keyword">this</span>.email = email;
    }


    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Long <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> id;
    }


    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(Long id)</span> </span>{
        <span class="hljs-keyword">this</span>.id = id;
    }


    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getFirstName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> firstName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setFirstName</span><span class="hljs-params">(String firstName)</span> </span>{
        <span class="hljs-keyword">this</span>.firstName = firstName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getLastName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> lastName;
    }


    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setLastName</span><span class="hljs-params">(String lastName)</span> </span>{
        <span class="hljs-keyword">this</span>.lastName = lastName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getEmail</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> email;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setEmail</span><span class="hljs-params">(String email)</span> </span>{
        <span class="hljs-keyword">this</span>.email = email;
    }

}
</code></pre>
<p>The defined UserDTO class can only hold four (4) fields: <code>id</code>, <code>firstName</code>, <code>lastName</code>, and <code>email</code>. It’s not capable of exposing or receiving more than this number of fields. The class also contains getter and setter methods for retrieving and assigning data to the fields.</p>
<h4 id="heading-step-2-create-mapper-methods-inside-a-utility-class">Step 2: Create Mapper Methods Inside a Utility Class</h4>
<p>Create a new file named <strong>UserMapper.java</strong> and put this piece of code into it:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserMapper</span> </span>{

    <span class="hljs-comment">// Convert Entity to DTO</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> UserDTO <span class="hljs-title">toDTO</span><span class="hljs-params">(UserEntity user)</span> </span>{

        <span class="hljs-keyword">if</span> (user == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;

        UserDTO dto = <span class="hljs-keyword">new</span> UserDTO();
        dto.setId(user.getId());
        dto.setFirstName(user.getFirstName());
        dto.setLastName(user.getLastName());
        dto.setEmail(user.getEmail());
        <span class="hljs-keyword">return</span> dto;
    }


    <span class="hljs-comment">// Convert DTO to Entity</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> UserEntity <span class="hljs-title">toEntity</span><span class="hljs-params">(UserDTO dto)</span> </span>{

        <span class="hljs-keyword">if</span> (dto == <span class="hljs-keyword">null</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
       UserEntity user = <span class="hljs-keyword">new</span> UserEntity(); 
        user.setFirstName(dto.getFirstName());
        user.setLastName(dto.getLastName());
        user.setEmail(dto.getEmail());

        <span class="hljs-keyword">return</span> user;
    }
</code></pre>
<p>The UserMapper class is a utility class that maps the UserEntity to a DTO and the DTO to an entity. This is where the bi-directional data transfer I talked about earlier comes into play. First, the UserEntity-DTO-direction involves retrieving the complete record from the database and transforming it into a streamlined object (void of unnecessary information) before it’s serialized and exposed to the client side through an API endpoint. </p>
<p>The DTO-UserEntity-direction involves taking the object from the client side as input into the system, but this time, to limit the client in terms of the number of data fields they can pass to the system. This object is received, mapped to an entity, and saved in the system. This is important when you don’t want the client to have access to certain critical fields (that would make your application vulnerable). That’s why software engineers always say, “Don’t trust the user”.</p>
<p>Let me give you a peek into what our UserEntity looks like:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> jakarta.persistence.*;

<span class="hljs-keyword">import</span> java.time.LocalDate;


<span class="hljs-meta">@Entity</span>

<span class="hljs-meta">@Table(name = "users")</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserEntity</span> </span>{


    <span class="hljs-meta">@Id</span>
    <span class="hljs-meta">@GeneratedValue(strategy = GenerationType.IDENTITY)</span>

    <span class="hljs-keyword">private</span> Long id;
    <span class="hljs-keyword">private</span> String firstName;
    <span class="hljs-keyword">private</span> String lastName;

    <span class="hljs-meta">@Column(unique = true)</span>
    <span class="hljs-keyword">private</span> String email;
    <span class="hljs-keyword">private</span> String password;
    <span class="hljs-keyword">private</span> String phoneNumber;
    <span class="hljs-keyword">private</span> String gender;
    <span class="hljs-keyword">private</span> LocalDate dateOfBirth;
    <span class="hljs-keyword">private</span> String address;
    <span class="hljs-keyword">private</span> String city;
    <span class="hljs-keyword">private</span> String state;
    <span class="hljs-keyword">private</span> String country;
    <span class="hljs-keyword">private</span> String profilePictureUrl;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> isVerified;
    <span class="hljs-keyword">private</span> LocalDate createdAt;
    <span class="hljs-keyword">private</span> LocalDate updatedAt;

    <span class="hljs-comment">// Constructors</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserEntity</span><span class="hljs-params">()</span> </span>{}

    <span class="hljs-comment">// Getters and Setters</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Long <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> id;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(Long id)</span> </span>{
        <span class="hljs-keyword">this</span>.id = id;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getFirstName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> firstName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setFirstName</span><span class="hljs-params">(String firstName)</span> </span>{
        <span class="hljs-keyword">this</span>.firstName = firstName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getLastName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> lastName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setLastName</span><span class="hljs-params">(String lastName)</span> </span>{
        <span class="hljs-keyword">this</span>.lastName = lastName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getEmail</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> email;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setEmail</span><span class="hljs-params">(String email)</span> </span>{
        <span class="hljs-keyword">this</span>.email = email;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPassword</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> password;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPassword</span><span class="hljs-params">(String password)</span> </span>{
        <span class="hljs-keyword">this</span>.password = password;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPhoneNumber</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> phoneNumber;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPhoneNumber</span><span class="hljs-params">(String phoneNumber)</span> </span>{
        <span class="hljs-keyword">this</span>.phoneNumber = phoneNumber;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getGender</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> gender;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setGender</span><span class="hljs-params">(String gender)</span> </span>{
        <span class="hljs-keyword">this</span>.gender = gender;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> LocalDate <span class="hljs-title">getDateOfBirth</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> dateOfBirth;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDateOfBirth</span><span class="hljs-params">(LocalDate dateOfBirth)</span> </span>{
        <span class="hljs-keyword">this</span>.dateOfBirth = dateOfBirth;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAddress</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> address;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAddress</span><span class="hljs-params">(String address)</span> </span>{
        <span class="hljs-keyword">this</span>.address = address;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getCity</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> city;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCity</span><span class="hljs-params">(String city)</span> </span>{
        <span class="hljs-keyword">this</span>.city = city;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getState</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> state;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setState</span><span class="hljs-params">(String state)</span> </span>{
        <span class="hljs-keyword">this</span>.state = state;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getCountry</span><span class="hljs-params">()</span> </span>{
       <span class="hljs-keyword">return</span> country;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCountry</span><span class="hljs-params">(String country)</span> </span>{
        <span class="hljs-keyword">this</span>.country = country;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getProfilePictureUrl</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> profilePictureUrl;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setProfilePictureUrl</span><span class="hljs-params">(String profilePictureUrl)</span> </span>{
        <span class="hljs-keyword">this</span>.profilePictureUrl = profilePictureUrl;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isVerified</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> isVerified;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setVerified</span><span class="hljs-params">(<span class="hljs-keyword">boolean</span> verified)</span> </span>{
        isVerified = verified;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> LocalDate <span class="hljs-title">getCreatedAt</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> createdAt;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCreatedAt</span><span class="hljs-params">(LocalDate createdAt)</span> </span>{
        <span class="hljs-keyword">this</span>.createdAt = createdAt;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> LocalDate <span class="hljs-title">getUpdatedAt</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> updatedAt;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUpdatedAt</span><span class="hljs-params">(LocalDate updatedAt)</span> </span>{
        <span class="hljs-keyword">this</span>.updatedAt = updatedAt;
    }

}
</code></pre>
<p>In the code snippet above, you can see that the UserDTO holds just four (4) fields, which are insensitive and safe to expose upon serialization. These fields are id, firstName, lastName, and email – unlike the UserEntity, which contains both the sensitive and insensitive fields. So, the not-safe-to-expose UserEntity maps to the safe-to-expose UserDTO. With that being done, the UserDTO object can be serialized and returned through an endpoint. You can now see why DTOs help us prevent exposing confidential information.</p>
<h3 id="heading-2-creating-custom-objects-and-handling-mapping-through-an-external-library">2. Creating Custom Objects and Handling Mapping Through an External Library</h3>
<p>Using an external library means adding a layer of abstraction to the mapping process. The library handles the stressful parts of the job for you, and it’s often a preferred choice for large-scale projects. In this article, we’re using <strong>MapStruct</strong> because it’s popular and easy to use. Maven will be our build tool. </p>
<h4 id="heading-step-1-add-the-dependency-to-your-project">Step 1: Add the dependency to your project</h4>
<p>Since you are using Maven as your build tool, open your pom.xml file and add this code:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- MapStruct API --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mapstruct<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mapstruct<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.5.5.Final<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Annotation processor plugin --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.maven.plugins<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-compiler-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.10.1<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">annotationProcessorPaths</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">path</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mapstruct<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mapstruct-processor<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.5.5.Final<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">path</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">annotationProcessorPaths</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
</code></pre>
<p>This will help download the dependency during the project build. </p>
<h4 id="heading-step-2-define-your-dto">Step 2: Define your DTO</h4>
<p>Use the <code>UserDTO.java</code> file given in step 1 of the first approach.</p>
<h4 id="heading-step-3-create-the-mapstruct-mapper-interface">Step 3: Create the MapStruct Mapper Interface</h4>
<p>Create a file and name it UserMapper.java, and add the code below to it:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.mapstruct.Mapper;
<span class="hljs-keyword">import</span> org.mapstruct.factory.Mappers;

<span class="hljs-meta">@Mapper(componentModel = "spring")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserMapper</span> </span>{
    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
    <span class="hljs-function">UserDTO <span class="hljs-title">toDTO</span><span class="hljs-params">(UserEntity user)</span></span>;
    <span class="hljs-function">UserEntity <span class="hljs-title">toEntity</span><span class="hljs-params">(UserDTO userDTO)</span></span>;
}
</code></pre>
<p>The UserMapper interface contains the INSTANCE field and two methods, namely toDTO and toEntity, that take in objects of types UserEntity and UserDTO, respectively, as arguments. The implementations of these methods are abstracted and handled by the library for us. </p>
<p>You can now use the mapper methods (toDTO and toEntity) in your Service or Controller.</p>
<h2 id="heading-how-to-create-dtos-from-two-or-multiple-objects">How to Create DTOs From Two or Multiple Objects</h2>
<p>This is one of the most important ways to use DTOs: creating DTOs from more than one entity and combining them as one, so that they can be returned in one API call or request. </p>
<p>There are many ways you can apply this technique and create complex response DTOs, based on the requirements of your project. The form or structure of your API response object might not be the same as the example given in this tutorial – but the same principle applies, which is simply creating individual DTOs and combining them into one DTO, which eventually serves as the response DTO.  </p>
<p>The example below isn’t super complex, but it’s sufficient to help you understand how this works so you can leverage the technique in creating more complex  API response objects. This example will combine DTOs of a doctor and their appointments.</p>
<h4 id="heading-step-1-create-the-dto-classes">Step 1: Create the DTO Classes</h4>
<p>Create a file named <strong>DoctorDto.java</strong> and add this code to it:</p>
<pre><code class="lang-java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DoctorProfileDTO</span> </span>{
    <span class="hljs-keyword">private</span> String doctorId;
    <span class="hljs-keyword">private</span> String fullName;
    <span class="hljs-keyword">private</span> String email;
    <span class="hljs-keyword">private</span> String specialization;

   <span class="hljs-comment">// No-args constructor</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DoctorProfileDTO</span><span class="hljs-params">()</span></span>{
    }

    <span class="hljs-comment">// Getter and Setter for doctorId</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDoctorId</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> doctorId;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDoctorId</span><span class="hljs-params">(String doctorId)</span> </span>{
        <span class="hljs-keyword">this</span>.doctorId = doctorId;
    }

    <span class="hljs-comment">// Getter and Setter for fullName</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getFullName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> fullName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setFullName</span><span class="hljs-params">(String fullName)</span> </span>{
        <span class="hljs-keyword">this</span>.fullName = fullName;
    }

    <span class="hljs-comment">// Getter and Setter for email</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getEmail</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> email;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setEmail</span><span class="hljs-params">(String email)</span> </span>{
        <span class="hljs-keyword">this</span>.email = email;
    }

    <span class="hljs-comment">// Getter and Setter for specialization</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getSpecialization</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> specialization;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSpecialization</span><span class="hljs-params">(String specialization)</span> </span>{
        <span class="hljs-keyword">this</span>.specialization = specialization;
    }
}
</code></pre>
<p>Create another one called <strong>AppointmentDto.java</strong> and include this code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppointmentDTO</span> </span>{
    <span class="hljs-keyword">private</span> String appointmentId;
    <span class="hljs-keyword">private</span> String appointmentDate;
    <span class="hljs-keyword">private</span> String status;
    <span class="hljs-keyword">private</span> String patientName;
    <span class="hljs-keyword">private</span> String patientEmail;

   <span class="hljs-comment">// No-args constructor</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AppointmentDTO</span><span class="hljs-params">()</span></span>{
    }

    <span class="hljs-comment">// Getter and Setter for appointmentId</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAppointmentId</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> appointmentId;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAppointmentId</span><span class="hljs-params">(String appointmentId)</span> </span>{
        <span class="hljs-keyword">this</span>.appointmentId = appointmentId;
    }

    <span class="hljs-comment">// Getter and Setter for appointmentDate</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAppointmentDate</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> appointmentDate;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAppointmentDate</span><span class="hljs-params">(String appointmentDate)</span> </span>{
        <span class="hljs-keyword">this</span>.appointmentDate = appointmentDate;
    }

    <span class="hljs-comment">// Getter and Setter for status</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getStatus</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> status;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setStatus</span><span class="hljs-params">(String status)</span> </span>{
        <span class="hljs-keyword">this</span>.status = status;
    }

    <span class="hljs-comment">// Getter and Setter for patientName</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPatientName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> patientName;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPatientName</span><span class="hljs-params">(String patientName)</span> </span>{
        <span class="hljs-keyword">this</span>.patientName = patientName;
    }

    <span class="hljs-comment">// Getter and Setter for patientEmail</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPatientEmail</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> patientEmail;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPatientEmail</span><span class="hljs-params">(String patientEmail)</span> </span>{
        <span class="hljs-keyword">this</span>.patientEmail = patientEmail;
    }
}
</code></pre>
<h4 id="heading-step-2-create-a-composite-dto-combining-both-entities">Step 2: Create a Composite DTO Combining both Entities</h4>
<p>Create a file named <strong>DoctorWithAppointmentsDTO.java</strong>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DoctorWithAppointmentsDTO</span> </span>{
    <span class="hljs-keyword">private</span> DoctorProfileDTO doctorProfile;
    <span class="hljs-keyword">private</span> List&lt;AppointmentDTO&gt; appointments;

    <span class="hljs-comment">// No-args constructor</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DoctorWithAppointmentsDTO</span><span class="hljs-params">()</span> </span>{
    }

    <span class="hljs-comment">// Getter and Setter for doctorProfile</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> DoctorProfileDTO <span class="hljs-title">getDoctorProfile</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> doctorProfile;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDoctorProfile</span><span class="hljs-params">(DoctorProfileDTO doctorProfile)</span> </span>{
        <span class="hljs-keyword">this</span>.doctorProfile = doctorProfile;
    }

    <span class="hljs-comment">// Getter and Setter for appointments</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;AppointmentDTO&gt; <span class="hljs-title">getAppointments</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> appointments;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAppointments</span><span class="hljs-params">(List&lt;AppointmentDTO&gt; appointments)</span> </span>{
        <span class="hljs-keyword">this</span>.appointments = appointments;
    }
}
</code></pre>
<h4 id="heading-step-3-create-a-mapper-class">Step 3: Create a Mapper Class</h4>
<p>Create a mapper class <strong>DoctorMapper.java</strong> containing the logic to map to the <strong>DoctorWithAppointmentsDTO</strong> class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MapperClass</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> DoctorWithAppointmentsDTO <span class="hljs-title">toDTO</span><span class="hljs-params">(Doctor doctor, List&lt;Appointment&gt; appointments)</span> </span>{

        DoctorProfileDTO doctorProfile = <span class="hljs-keyword">new</span> DoctorProfileDTO();
        doctorProfile.setDoctorId(doctor.getId());
        doctorProfile.setFullName(doctor.getFullName());
        doctorProfile.setEmail(doctor.getEmail());
        doctorProfile.setSpecialization(doctor.getSpecialization());

        List&lt;AppointmentDTO&gt; appointmentDTOs = appointments.stream().map(appt -&gt; {
            AppointmentDTO dto = <span class="hljs-keyword">new</span> AppointmentDTO();
            dto.setAppointmentId(appt.getId());
            dto.setAppointmentDate(appt.getDate().toString()); 
            dto.setStatus(appt.getStatus().name());
            dto.setPatientName(appt.getPatient().getName());
            dto.setPatientEmail(appt.getPatient().getEmail());
            <span class="hljs-keyword">return</span> dto;
        }).toList();

        DoctorWithAppointmentsDTO doctorWithAppointment = <span class="hljs-keyword">new</span> DoctorWithAppointmentsDTO();
        doctorWithAppointment.setDoctorProfile(doctorProfile);
        doctorWithAppointment.setAppointments(appointmentDTOs);

        <span class="hljs-keyword">return</span> doctorWithAppointment;
    }
}
</code></pre>
<p>From the example above, you can see that two separate DTOs (AppointmentDTO and DoctorProfileDTO) were created before the composite DTO, DoctorWithAppointmentsDTO was created. The composite DTO class (DoctorWithAppointmentsDTO) contains fields that hold the instances of the Appointment and DoctorProfile DTOs. The mapper class takes in the Doctor and a list of Appointment entities as arguments, maps them to DoctorProfileDTO and AppointmentDTO, respectively. Finally, the fields for the composite DTO class are set using the DTO objects mapped from the entities.</p>
<p>The <strong>DoctorWithAppointmentsDTO,</strong> when serialised and returned through an endpoint, should give you an output like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"doctorProfile"</span>: {
    <span class="hljs-attr">"doctorId"</span>: <span class="hljs-string">"abc123"</span>,
    <span class="hljs-attr">"fullName"</span>: <span class="hljs-string">"Dr. Susan Emeka"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"suzan.emeka@example.com"</span>,
    <span class="hljs-attr">"specialisation"</span>: <span class="hljs-string">"Cardiology"</span>
  },
  <span class="hljs-attr">"appointments"</span>: [
    {
      <span class="hljs-attr">"appointmentId"</span>: <span class="hljs-string">"appt001"</span>,
      <span class="hljs-attr">"appointmentDate"</span>: <span class="hljs-string">"2025-07-10T09:00:00"</span>,
      <span class="hljs-attr">"status"</span>: <span class="hljs-string">"CONFIRMED"</span>,
      <span class="hljs-attr">"patientName"</span>: <span class="hljs-string">"James Agaji"</span>,
      <span class="hljs-attr">"patientEmail"</span>: <span class="hljs-string">"james.agaji@example.com"</span>
    },
 {
      <span class="hljs-attr">"appointmentId"</span>: <span class="hljs-string">"appt002"</span>,
      <span class="hljs-attr">"appointmentDate"</span>: <span class="hljs-string">"2025-08-12T07:05:08"</span>,
      <span class="hljs-attr">"status"</span>: <span class="hljs-string">"CONFIRMED"</span>,
      <span class="hljs-attr">"patientName"</span>: <span class="hljs-string">"Jane Augustine"</span>,
      <span class="hljs-attr">"patientEmail"</span>: <span class="hljs-string">"jane.augustine@example.com"</span>
    }
  ]
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you’re a software engineer who’s concerned with privacy and efficiency, using DTOs in your applications is a must.</p>
<p>In this article, you’ve learned what DTOs are as well as the main approaches for creating and using them. Take the time to go through the code snippets given in this article and practice with them until you’re comfortable implementing them yourself. Thanks for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Spring vs Spring Boot: How to Choose the Right Java Framework ]]>
                </title>
                <description>
                    <![CDATA[ The Java programming language is a favourite among solo devs and large teams alike. It’s popular for many reasons and use cases, including its mature ecosystem, stable support, efficiency, and reliability. If you’re learning Java with the end goal of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/spring-vs-spring-boot-choosing-a-java-framework/</link>
                <guid isPermaLink="false">687ecc61edf675fee8ff0271</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Spring ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Springboot ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Augustine Alul ]]>
                </dc:creator>
                <pubDate>Mon, 21 Jul 2025 23:25:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753140286088/7294bd87-8940-450f-aa05-cef68a1c2604.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Java programming language is a favourite among solo devs and large teams alike. It’s popular for many reasons and use cases, including its mature ecosystem, stable support, efficiency, and reliability.</p>
<p>If you’re learning Java with the end goal of building applications, you’ll need to be able to choose a suitable Java framework (a collection of necessary pre-built tools and libraries) to make development easier once you know the fundamentals. </p>
<p>There are many Java frameworks out there that help you complete different tasks, such as Jakarta EE (formerly Java EE, an enterprise-level framework, used for large-scale applications), JSF (or JavaServer Faces, a UI framework for developing Java web interfaces), Spring, Spring Boot, and others. </p>
<p>You may have heard of Spring and Spring Boot by now, as they are very popular and commonly used by Java devs. In this article, you will learn:</p>
<ul>
<li><p>What the Spring and Spring Boot frameworks are.</p>
</li>
<li><p>Their real-world use cases and how to get started building with them.</p>
</li>
<li><p>The key differences between Spring and Spring Boot.</p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To fully understand the content of this article, you should have a good working knowledge of the Java programming language, be familiar with the concept of APIs (<strong>Application Programming Interfaces</strong>), and know how to use Java project build tools – especially Maven, as it’s the build tool we’ll use for this article’s code examples.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-the-spring-framework">What is the Spring Framework?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-spring-boot-framework">What is the Spring Boot Framework?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-core-differences-between-spring-and-spring-boot">Core Differences Between Spring and Spring Boot</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-world-example">Real World Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-between-spring-and-spring-boot">How to Choose Between Spring and Spring Boot</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-the-spring-framework">What is the Spring Framework?</h2>
<p>Spring is a framework used for building modern enterprise-grade applications. It’s primarily used for Java, but it’s also compatible with the Kotlin and Groovy programming languages, too. This means that you can use Kotlin and Groovy to develop applications in Spring.</p>
<p>Spring provides a clear paradigm you can follow for building and configuring applications for easy deployment on any platform you choose.</p>
<p>At the core of the Spring framework is its robust infrastructure support. It internally handles implementing key components that are required for the safety and overall functionality of enterprise applications. It does this using modules such as:</p>
<ul>
<li><p>Spring JDBC</p>
</li>
<li><p>Spring MVC</p>
</li>
<li><p>Spring Security</p>
</li>
<li><p>Spring AOP</p>
</li>
<li><p>Spring ORM and </p>
</li>
<li><p>Spring Test</p>
</li>
</ul>
<p>These let developers focus on the business logic of the application instead of worrying about implementing or writing the code for the components/modules from scratch. This saves significant development time.</p>
<h3 id="heading-why-use-spring">Why use Spring?</h3>
<p>Spring does a lot of heavy lifting in terms of reducing excessive infrastructure code through its modules compared to legacy Java frameworks. This is one of the reasons it’s so popular.</p>
<p>For instance, when it comes to handling dependencies in Spring, you just have to define the dependency using the <code>@Bean</code> annotation in a configuration class, replacing the older approach of adding the dependency in an XML file.</p>
<p>Spring then adds the bean to an IoC (Inversion of Control) container, and makes the bean available to be utilised during runtime, also handling the lifecycle and wiring automatically.</p>
<p>Here is a simple code illustration of the configuration class below:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppConfig</span></span>{

<span class="hljs-meta">@Bean</span>

<span class="hljs-function"><span class="hljs-keyword">public</span> DataSource <span class="hljs-title">dataSource</span><span class="hljs-params">()</span> </span>{

    DriverManagerDataSource ds = <span class="hljs-keyword">new</span> DriverManagerDataSource();

    ds.setUrl(<span class="hljs-string">"jdbc:mysql://localhost:3306/mydb"</span>);

    ds.setUsername(<span class="hljs-string">"user"</span>);

    ds.setPassword(<span class="hljs-string">"pass"</span>);

    <span class="hljs-keyword">return</span> ds;

  }


}
</code></pre>
<p>Here’s the class where the resource/dependency is utilised:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Component</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserRepository</span> </span>{

<span class="hljs-keyword">private</span> DataSource dataSource;

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">UserRepository</span><span class="hljs-params">(DataSource dataSource)</span></span>{

      <span class="hljs-keyword">this</span>.dataSource = dataSource;

}

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">connectToDb</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> SQLException </span>{

        Connection conn = dataSource.getConnection();

        System.out.println(<span class="hljs-string">"Connected to DB via Spring!"</span>);

        conn.close();

    }

}
</code></pre>
<p>These code snippets demonstrate how dependency injection is implemented using Spring’s <code>@Bean</code> and <code>@Component</code> annotations. In the code is a configuration class and a second class where the <code>DataSource</code> is injected and used. This shows a simplistic approach to dependency management in Spring.</p>
<h3 id="heading-key-components-of-the-spring-framework">Key Components of the Spring Framework</h3>
<p>Spring is made up of several components, each serving distinct roles (as shown in the image below):</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdVmXBnm1fS-t0pN7w-zAglYvKrx37zoEZ4HdeszACcU8Ig4PFs_mKlfU49SALDAtrWUE1bj8bZ6lnvDoc4SoM_VxH5Nerime9uuNlIc5S6picvT3ho6Jv8dEmFTv7zrOKFNVDMxg?key=Zq-Isk9ZAG_nIZ1YfHDMRfMs" alt="Image containing the Spring Framework Runtime Components" width="581" height="448" loading="lazy"></p>
<p>Image <a target="_blank" href="https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/overview.html">source</a> | Overview of the Spring Framework</p>
<p>These components collectively provide useful functionalities that make Spring a robust framework. Think of them as parts that make up a whole. Let me briefly explain each of the components and their various roles for easy understanding.</p>
<h4 id="heading-data-accessintegration">Data Access/Integration:</h4>
<p>This component enables easy interaction with databases and other data sources. It contains several modules (JDBC, ORM, OXM, JMS and Transaction Management), each performing unique functions.</p>
<p>These modules provide fine-grained abstraction for tasks like executing SQL queries, integrating with ORM frameworks (for example, Hibernate), handling XML data binding, messaging, and managing transactions, while working in a Spring-based application<strong>.</strong> </p>
<h4 id="heading-web">Web:</h4>
<p>The Web component makes interaction between the client side (through HTTP request) and the core business logic possible in a Spring application. It consists of four modules (Web, Web-Servlet, Web-Struts, and Web-Portlet), each serving a specific function:</p>
<ul>
<li><p>The <strong>Web</strong> module enables multipart file upload functionality and initialization of the IoC container.</p>
</li>
<li><p><strong>Web-Servlet</strong> module provides an MVC (Model View Controller) Implementation for web applications.</p>
</li>
<li><p>The <strong>Web-Struts</strong> module integrates Struts into Spring by using support classes.</p>
</li>
<li><p>The <strong>Web-Portlet</strong> module supports MVC implementation for use in a portlet environment.</p>
</li>
</ul>
<h4 id="heading-aop-and-instrumentation">AOP and Instrumentation:</h4>
<p>AOP provides the implementation that makes it possible to ensure the separation of “cross-cutting concerns” in your application from the business logic, leading to cleaner and more organized code that’s free from clutter and repetition.</p>
<p>Instead of writing these <strong>concerns</strong> everywhere in your classes, you just define them in <strong>aspects</strong> and they are injected for you by Spring when the program needs them. These <strong>concerns</strong> could be logging, security, or transactions.</p>
<h4 id="heading-instrumentation">Instrumentation:</h4>
<p>This enables class instrumentation support, which ensures class bytecode modification.</p>
<h4 id="heading-core-container">Core Container:</h4>
<p>Core Container as the name implies, is a crucial part of Spring. It is responsible for some of the unique features that make the Spring Framework desired and popular: IoC (Inversion of Control) and dependency injection.</p>
<p>Core Container is made of Beans, Core, Context and Expression Language modules. These modules all have unique, yet complementary properties.</p>
<h4 id="heading-test">Test:</h4>
<p>The Test component provides a suitable approach to testing Spring applications, and it integrates smoothly with JUnit or TestNG. It goes as far as providing mock objects that can be used to test different components of your application in either an isolated or Spring-managed environment, helping you achieve a robust and reliable software application.</p>
<h2 id="heading-what-is-the-spring-boot-framework">What is the Spring Boot Framework?</h2>
<p>Spring Boot is an open-source framework built on top of Spring for developing robust stand-alone applications that you can “easily run”. The major purpose for which Spring Boot was created was to further simplify the process of configuring and running Spring applications. </p>
<p>Spring Boot enforces an opinionated approach to development and provides extra useful features not contained in Spring. Let’s learn a bit more about how it works.</p>
<h3 id="heading-key-features-of-the-spring-boot-framework">Key Features of the Spring Boot Framework</h3>
<p>Spring Boot, being part of the Spring ecosystem, inherits most Spring functionalities, but contains additional features not included in Spring. Let me explain these unique features briefly: </p>
<h4 id="heading-auto-configuration">Auto-configuration</h4>
<p>Spring Boot automatically configures dependencies present in the classpath (location where the Java runtime looks for classes/resources during compilation) through the <code>@SpringBootApplication</code> annotation. This is a combination of <code>@EnableAutoConfiguration</code>, <code>@Configuration</code>, and <code>@ComponentScan</code>. This auto-configuration saves effort in writing boilerplate code for configuring dependencies/beans (as you have to do with Spring). </p>
<p>Here’s how you can use the <code>@SpringBootApplication</code> annotation for auto-configuration in Spring Boot applications:</p>
<pre><code class="lang-java">      <span class="hljs-meta">@SpringBootApplication</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{

        SpringApplication.run(MyApp.class, args);

    }

}
</code></pre>
<h4 id="heading-starter-dependencies">Starter dependencies</h4>
<p>Starter dependencies provide a cleaner and less verbose way of managing dependencies in Spring Boot. Essentially, it bundles a set of complementary dependencies that perform a common task into one, meaning you don’t need to manually declare every single dependency that is part of the starter bundle.</p>
<p>Starter dependencies in Spring Boot follow the naming convention spring-boot-starter-*, where the asterisk represents the name of the particular dependency.</p>
<p>Some common starter dependencies in Spring Boot are: </p>
<ul>
<li><p>spring-boot-starter-web</p>
</li>
<li><p>spring-boot-starter-aop</p>
</li>
<li><p>spring-boot-starter-data-jdbc</p>
</li>
<li><p>spring-boot-starter-data-jpa</p>
</li>
<li><p>spring-boot-starter-data-rest</p>
</li>
</ul>
<h4 id="heading-actuator">Actuator</h4>
<p>Actuator is a module in the Spring Boot framework that lets you monitor Spring Boot applications after/during development. It provides both inbuilt and customizable endpoints you can use for application health checks, metrics, and diagnostics.</p>
<p>These are some of the commonly used endpoints:</p>
<ul>
<li><p>/actuator/health: Provides health status. </p>
</li>
<li><p>/actuator/metrics: Displays various application metrics. </p>
</li>
<li><p>/actuator/info: Shows general application information. </p>
</li>
<li><p>/actuator/env: Exposes environment properties. </p>
</li>
<li><p>/actuator/beans: Lists all Spring beans. </p>
</li>
<li><p>/actuator/threaddump: Performs a thread dump. </p>
</li>
<li><p>/actuator/shutdown: Allows graceful shutdown (disabled by default).</p>
</li>
</ul>
<h4 id="heading-command-line-tool">Command line tool</h4>
<p>The Spring Boot command line tool is an interface that helps you rapidly develop and test your Spring Boot applications. It contains commands you can use to:</p>
<ul>
<li><p>Run Spring Boot applications from the terminal directly (spring run).</p>
</li>
<li><p>Manage application dependencies and versions</p>
</li>
<li><p>Initialize a new Spring Boot project</p>
</li>
<li><p>Compile and test Java/Groovy scripts.</p>
</li>
</ul>
<h4 id="heading-additional-configuration-through-applicationproperties-and-applicationyml-files">Additional configuration (through application.properties and application.yml files)</h4>
<p><code>application.properties</code> and <code>application.yml</code> files are two formats you can use to configure your Spring Boot application settings. They are in key-value and YAML formats, respectively. They let you configure ports, data source, logging, caching, and so on.</p>
<pre><code class="lang-plaintext"> server.port=8081
 spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring.datasource.username=root

spring.datasource.password=secret

logging.level.org.springframework=DEBUG
</code></pre>
<p>This is an example of an <code>application.properties</code> file for a Spring Boot project. You can see that the port, datasource and logging credentials have been configured.</p>
<h4 id="heading-embedded-web-server">Embedded Web Server</h4>
<p>Spring Boot comes with embedded web servers (Tomcat, Jetty, and Undertow) that are used to easily serve compiled Spring Boot applications in the form of jar files without needing to deploy them to an external, dedicated web server. This simplifies deployment, especially in a microservice architecture and containerised environments, as applications can be easily run using the command:</p>
<pre><code class="lang-java">java -jar my-springboot-app.jar
</code></pre>
<p>Note that Spring Boot cannot exist without Spring (but Spring can exist without Jakarta EE and other Java legacy frameworks created before it). Spring Boot is part of the Spring platform. It is like the extra icing on top of the cake that makes it sweeter.</p>
<p>Of course, you can still have your cake without the icing. Technically, you can say Spring Boot is an additional layer that still needs Spring to run as its underlying infrastructure.</p>
<h2 id="heading-core-differences-between-spring-and-spring-boot">Core Differences Between Spring and Spring Boot</h2>
<p>You should now be familiar with the fundamentals of the Spring and Spring Boot frameworks. So let’s talk a bit more about how they differ, x-raying their strengths and areas of weakness.</p>
<h3 id="heading-configuration">Configuration</h3>
<p>Configuration in Spring is more tedious when compared to Spring Boot, since you’ll need to manually add the configurations for your project in Spring. This requires more code for setting up the various components you need for a project.</p>
<p>Meanwhile, configuration in Spring Boot is easier as you can use the <a target="_blank" href="https://start.spring.io/">Spring Initializr website</a>. There, you just have to select the dependencies for the project, add a little more setup, and then download the zip file that contains the configuration for the project. It requires minimal steps to do this, which improves your productivity and makes the learning curve easier.</p>
<h3 id="heading-external-server-and-deployment">External Server and Deployment</h3>
<p>Spring requires that you deploy your applications to an external server like Tomcat in the form of a WAR (<strong>Web Application Archive</strong> or <strong>Web Application Resource</strong>) file.</p>
<p>Spring Boot, on the other hand, comes with an embedded server like Tomcat, which you can use for running/deploying stand-alone executable applications as JAR (or <strong>Java ARchive</strong>) files. This is why Spring Boot is highly preferred for developing microservices since it is relatively easy to build applications and run them.</p>
<h3 id="heading-level-of-control">Level of Control</h3>
<p>Both Spring and Spring Boot utilise the Inversion of Control (or IoC) paradigm for managing dependencies. Spring gives you more control over the application because you have the flexibility to initiate configurations as needed. But Spring Boot handles more of the application management internally, giving you little room for control over the application configuration, as it auto-generates configurations that may not be needed for a particular project. This can lead to redundant code. </p>
<h3 id="heading-suitability-for-development">Suitability for Development</h3>
<p>Spring, like Java EE, is preferred for large-scale enterprise applications due to its fine-grained configuration control that is invaluable, especially for complex and critical performance applications like banking, healthcare, and e-commerce. It provides great flexibility, which makes it suitable for integrating with Java EE components and other enterprise-grade technologies and legacy systems. </p>
<p>Spring Boot is not a common choice for large-scale monolithic applications, even though it can be used in these cases. It is more suitable for developing stand-alone applications or microservices where rapid development with embedded server support is prioritized over granular configuration and control.</p>
<h3 id="heading-production-ready-features">Production-ready features</h3>
<p>In Spring, extra effort is needed to manually set up health checks, metrics and monitoring of your application. Whereas, Spring Boot comes with the <strong>actuator</strong>, which is a built-in tool that is useful for metrics, application monitoring, and for carrying out health checks. You just need to add this dependency to your <strong>pom.xml</strong> file</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-actuator<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<p>After that, you can monitor your application by visiting the desired actuator endpoint that exposes the needed information. Find a list of the common actuator endpoints you can visit under the <strong>Actuator</strong> subsection of the <strong>What is Spring Boot</strong> section above. </p>
<h2 id="heading-real-world-example">Real World Example</h2>
<p>Let’s look at an example of how to build a simple REST API endpoint in both Spring and Spring Boot frameworks:</p>
<h3 id="heading-building-with-the-spring-framework">Building with the Spring Framework</h3>
<p>In this API example, the technologies/dependencies we’ll use are:</p>
<ul>
<li><p>Java (Programming Language)</p>
</li>
<li><p>Maven (the build tool for the project)</p>
</li>
<li><p>Tomcat (servlet container)</p>
</li>
<li><p>Operating System (Mac/Linux/Windows)</p>
</li>
<li><p>Core Spring framework with the Spring MVC module</p>
</li>
<li><p>Jackson Databind: for JSON serialisation</p>
</li>
</ul>
<p>Note that we’ll be using Maven here as our build tool (and for the Spring Boot example that follows, too) because of its simplicity and beginner friendliness.</p>
<h4 id="heading-step-1-create-appconfigjava-file">Step 1: Create AppConfig.java file</h4>
<p>This is the configuration class that sets on Spring MVC properties through the <code>@EnableWebMvc</code> annotation, scans for the controllers in their packages through the <code>@ComponentScan</code> annotation, and configures other needed defaults automatically.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Configuration</span>

<span class="hljs-meta">@EnableWebMvc</span>

<span class="hljs-meta">@ComponentScan(basePackages = "com.example.controller")</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WebMvcConfigurer</span> </span>{

}
</code></pre>
<h4 id="heading-step-2-create-webappinitializerjava">Step 2: Create WebAppInitializer.java</h4>
<p>This is the class that replaces <code>web.xml</code> (That was used in older versions.) It creates the Spring application context and connects to the <code>AppConfig</code> file for configuration. </p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebAppInitializer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">WebApplicationInitializer</span> </span>{  
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onStartup</span><span class="hljs-params">(ServletContext servletContext)</span> </span>{

    <span class="hljs-comment">// Create annotation-based web context</span>

    AnnotationConfigWebApplicationContext context = 

      <span class="hljs-keyword">new</span> AnnotationConfigWebApplicationContext();

    context.register(AppConfig.class);

    // Register DispatcherServlet

    DispatcherServlet servlet = <span class="hljs-keyword">new</span> DispatcherServlet(context);

    ServletRegistration.Dynamic registration = 

      servletContext.addServlet(<span class="hljs-string">"dispatcher"</span>, servlet);

    registration.setLoadOnStartup(<span class="hljs-number">1</span>);

    registration.addMapping(<span class="hljs-string">"/"</span>);

  }

}
</code></pre>
<h4 id="heading-step-3-add-the-controller-logic">Step 3: Add the <strong>controller</strong> logic</h4>
<p>Create a <code>HelloController.java</code> file and add the controller logic. It receives a <strong>GET</strong> request and returns “Hello from Spring Framework!” </p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span> <span class="hljs-comment">// Combines @Controller + @ResponseBody</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloController</span> </span>{

  <span class="hljs-meta">@GetMapping("/hello")</span>

  <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">hello</span><span class="hljs-params">()</span> </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from Spring Framework!"</span>;

  }

}
</code></pre>
<h4 id="heading-step-4-add-dependencies">Step 4: Add Dependencies</h4>
<p>Include all the dependencies for the project in a <strong>pom.xml</strong> file, since we’re using Maven as the build tool.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-webmvc<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>6.1.6<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span> <span class="hljs-comment">&lt;!-- Latest Spring 6.x --&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jackson-databind<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.17.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span> <span class="hljs-comment">&lt;!-- For JSON support --&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<h4 id="heading-step-5-build-and-deploy-the-api">Step 5: Build and Deploy the API</h4>
<p>Lastly, you have to build the application into a WAR (Web Archive) file and deploy it to a servlet container (like Tomcat, Jetty, or whichever is suitable) before the application can be made accessible.</p>
<p>Follow the steps given below to deploy to a Tomcat server:</p>
<ol>
<li><h4 id="heading-package-the-app-as-a-war-file">Package the app as a WAR file</h4>
</li>
</ol>
<p>If Maven is your build tool for the project, add this configuration code to your Pom.xml file:</p>
<p><code>&lt;packaging&gt;war&lt;/packaging&gt;</code></p>
<p>Then, build using the command:</p>
<p><code>./mvnw clean package</code> </p>
<p>After this, your WAR file will be created and stored in <code>target/yourapp.war</code></p>
<ol start="2">
<li><h4 id="heading-deploy-your-war-file-to-a-servlet-container-in-this-case-tomcat">Deploy your WAR file to a servlet container (in this case, Tomcat)</h4>
</li>
</ol>
<p>At this point, you can choose to either deploy your WAR file to a remote or local servlet container on your machine. Let’s deploy to a local servlet container since you can easily practice this on your own.</p>
<ul>
<li><p>Download and install Apache Tomcat from the official website https://tomcat.apache.org/</p>
</li>
<li><p>Enter the <strong>webapps</strong> directory by entering the command <strong>cd path-to-tomcat/webapps/</strong></p>
</li>
<li><p>Copy your WAR file into the folder </p>
</li>
</ul>
<p>           <code>cp /path-to-your/target/yourapp.war</code> </p>
<ul>
<li>Start the Tomcat web server. </li>
</ul>
<p>On Linux/Mac OS, run:</p>
<p><code>./bin/startup.sh</code> </p>
<p>On Windows, do:</p>
<p><code>startup.bat</code>.</p>
<p>You should see a link similar to this on your terminal window:</p>
<p><code>http://localhost:8080/yourapp</code></p>
<p>Go ahead and click on it. And there you go!</p>
<h3 id="heading-building-with-the-spring-boot-framework">Building with the Spring Boot Framework</h3>
<p>The different technologies from the Spring example that I will use are simply the Embedded Tomcat server over the Tomcat servlet container. And here, of course, we’ll be using Spring Boot as the development framework instead of Spring.</p>
<p>In Spring Boot, you can either go straight into your IDE and start creating the needed files and configurations for your project, or you can choose to use the <a target="_blank" href="https://start.spring.io/">Spring initializr</a> to select dependencies and generate the base files and configurations for your project. The second option is preferred since it is less tedious.</p>
<h4 id="heading-step-1-choose-necessary-dependencies-for-your-project-and-download-the-zip-file">Step 1: Choose Necessary Dependencies for Your Project and Download the Zip File</h4>
<p>Open the <a target="_blank" href="https://start.spring.io/">Spring initializr</a> website, choose the project as Maven, language as Java, and fill in the project metadata. For this project, fill in the Artifact as Hello. </p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe41zF3IjWT8f8yW1kNlD4in3jhPev8DAm6lrIXf1anqZiZnCQtHfEavLP1u0DxMJ-h8crZVfsVcAdrEYxFHxuGmHF5PyjOEblTJEEL5vKx3XY1LYYbwY3CSyZAUfD7yv4nNpud7g?key=Zq-Isk9ZAG_nIZ1YfHDMRfMs" alt="Image showing how to correctly fill the metadata for a Spring Boot project from the Spring initializer website" width="1285" height="511" loading="lazy"></p>
<p>Choose jar for packaging, and then select the dependencies for the project. For this article, we will use only the Spring Web. Then click on the generate button. </p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc_5puGjgNKRvgAp4MrC_J_8o4ZMmJ4ozms6WDCJbsboF5oC7YarspzS65qXfFfSZtSkPJxLEcY11Or64irPvWnkmz9A0vxIh5BdFMJw_7lISxBqPyU78Uxa-s23AlbXKWIYIPLHw?key=Zq-Isk9ZAG_nIZ1YfHDMRfMs" alt="Image showing how to choose dependencies for a Spring Boot project from the Spring Initializer website" width="1600" height="739" loading="lazy"></p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcAi17ltnglcLuD6iDy0MLb6j2ANa4ssJKD6WdaPyQ0RERpOazdOcBfTWwFxix6U2Om9UPOxH-qy3k5gm6BbFTBdGf0PR9KH3EQvWfYucfpFBMM2EKb5DfMB8jcdj0xqYHfYbvOfg?key=Zq-Isk9ZAG_nIZ1YfHDMRfMs" alt="Image showing how to generate and download the files containing the configuration and dependencies for the Spring Boot project" width="828" height="683" loading="lazy"></p>
<p>This downloads a zip file to your machine containing the boilerplate code with which you can build your application.</p>
<h4 id="heading-step-2-create-the-controller-hellocontrollerjava">Step 2: Create the <strong>Controller (HelloController.java)</strong></h4>
<p>Unzip the downloaded file from step 1, and open it in your preferred IDE (or Integrated Development Environment). Navigate to the Hello/src/main/java/com/example/Hello directory, where you should already have the HelloApplication.java file, and add the HelloController.java file: </p>
<pre><code class="lang-java"><span class="hljs-meta">@RestController</span>

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloController</span> </span>{

  <span class="hljs-meta">@GetMapping("/hello")</span>

  <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">hello</span><span class="hljs-params">()</span> </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from Spring Boot!"</span>;

  }

}
</code></pre>
<h4 id="heading-step-3-build-and-run-the-application">Step 3: Build and run the application</h4>
<p>On your terminal, run the following commands: <code>mvn clean package &amp;&amp; java -jar target/your-app.jar</code>. You can then access the endpoint on http://localhost:8080/hello. When you click on the link, you should see <code>Hello from Spring Boot!</code> on your screen.</p>
<h2 id="heading-how-to-choose-between-spring-and-spring-boot">How to Choose Between Spring and Spring Boot</h2>
<p>Spring and Spring Boot are both popular Java frameworks for building robust software solutions. And as you have learned from the earlier part of this tutorial, they have many common features (since Spring Boot is built atop Spring). </p>
<p>But there are a few key areas where they differ. First is the format of their packaged files: Spring is packaged to WAR, and Spring Boot to JAR. Also, Spring Boot comes with an embedded web server while Spring requires an external servlet container.</p>
<p>The embedded web server that comes with Spring Boot makes it easy to run Spring Boot applications during development and in production without needing an external servlet container. Meanwhile, traditional Spring requires developers to deploy to an external servlet container. This makes Spring Boot suitable for rapid development and deployment of stand-alone applications or microservices, as it not only saves time but also reduces setup complexity and infrastructure requirements.</p>
<p>Furthermore, Spring’s fine-grained configuration and ease of integration with legacy systems and tools make it the desired choice for developing highly customizable enterprise-grade applications. This is unlike Spring Boot, which relies on the convention-over-configuration philosophy, providing auto-configuration for reduced development time.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building enterprise-grade and microservices applications with Java is much easier using the Spring and Spring Boot frameworks. </p>
<p>In this article, you’ve learned how these two frameworks work, along with their areas of strength and drawbacks.</p>
<p>This article doesn’t intend to favour one framework over the other, but rather to show in detail how they differ and their unique characteristics. </p>
<p><strong>But to summarize:</strong></p>
<ul>
<li><p>Use Spring when building highly customized legacy-integrated enterprise systems.</p>
</li>
<li><p>Use Spring Boot for REST APIs, microservices, or cloud-native apps.</p>
</li>
</ul>
<p>The next time you are faced with a project requiring you to choose a similar framework, it is imperative to carefully weigh your choices and select the framework that closely fits your task. Happy coding!</p>
<h3 id="heading-references">References</h3>
<ol>
<li><p><a target="_blank" href="https://spring.io/projects/spring-framework/">Spring Framework Official Documentation</a> </p>
</li>
<li><p><a target="_blank" href="https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/overview.html">Baeldung – Introduction to Spring Framework</a></p>
</li>
<li><p><a target="_blank" href="https://ellow.io/spring-vs-spring-boot/">Ellow. Spring vs Spring Boot: An In-depth Comparison</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
