<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hamza Nassour on Medium]]></title>
        <description><![CDATA[Stories by Hamza Nassour on Medium]]></description>
        <link>https://medium.com/@hamza.nassour13?source=rss-4aed7f746d32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zqPQJRzPVU2RmbPAYxDerg.jpeg</url>
            <title>Stories by Hamza Nassour on Medium</title>
            <link>https://medium.com/@hamza.nassour13?source=rss-4aed7f746d32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:18:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamza.nassour13/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Nested Classes in Java: A Comprehensive Guide]]></title>
            <link>https://medium.com/javarevisited/nested-classes-in-java-a-comprehensive-guide-177a8069f8ce?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/177a8069f8ce</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[nested-classes]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[inner-class]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 16:53:40 GMT</pubDate>
            <atom:updated>2024-12-09T12:43:28.361Z</atom:updated>
            <content:encoded><![CDATA[<p>Nested classes are classes defined within other classes. They allow logical grouping and better encapsulation. In Java, there are four types of nested classes:</p><ul><li><strong>Inner Classes</strong></li><li><strong>Static Nested Classes</strong></li><li><strong>Local Classes</strong></li><li><strong>Anonymous Classes</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kBmrfvpXOEGDD7g0" /></figure><h3>Types of Nested Classes in Java</h3><p>Each nested class type in Java serves a specific purpose. Let’s explore them in detail, with practical examples and scenarios of when to use each.</p><h3>Inner Classes in Java</h3><p>An inner class is a class defined inside another class, known as the outer class. It has access to the instance variables and methods of its enclosing class. Inner classes are often used in situations where each instance of the inner class is tightly linked to a specific instance of the outer class.</p><pre>// Outer class<br>public class OuterClass {<br>    private int outerValue = 10;<br><br>    // Inner class<br>    public class InnerClass {<br>        public void display() {<br>            System.out.println(&quot;Outer value is &quot; + outerValue);<br>        }<br>    }<br>}</pre><p>In this example, the inner class accesses the private member of its enclosing outer class.</p><h4>How do you create an instance of an inner class in Java?</h4><p>To instantiate an inner class in Java, you first need an instance of the outer class. Since inner classes are tied to the outer class’s instance, they cannot exist independently, as the inner object holds an implicit reference to the outer object.</p><p>To create an instance of an inner class, start by instantiating the outer class. Then, use the outer class instance to instantiate the inner class using this syntax:</p><pre>// Instantiating<br>OuterClass outerInstance = new OuterClass();<br>OuterClass.InnerClass innerInstance = outerInstance.new InnerClass();<br>innerInstance.display();</pre><h4>Real-World Example of Inner Classes: The Iterator Inner Class in Java’s ArrayList</h4><p>A well-known real-life example of an inner class in Java’s standard library is the Iterator inner class within the ArrayList class. In Java, ArrayList is a widely used implementation of the List interface, and it provides an Iterator inner class to enable sequential traversal of its elements.</p><p>The Iterator inner class allows developers to iterate through the elements of an ArrayList without exposing its internal structure. This encapsulation ensures that the internal workings of the ArrayList remain hidden while providing an efficient mechanism to access its elements.</p><p>Here’s an example of how the Iterator inner class is used with an ArrayList:</p><pre>import java.util.ArrayList;<br>import java.util.Iterator;<br><br>public class Main {<br>    public static void main(String[] args) {<br>        ArrayList&lt;String&gt; fruits = new ArrayList&lt;&gt;();<br>        fruits.add(&quot;Apple&quot;);<br>        fruits.add(&quot;Banana&quot;);<br>        fruits.add(&quot;Orange&quot;);<br><br>        // Using the Iterator inner class to traverse the ArrayList<br>        Iterator&lt;String&gt; iterator = fruits.iterator();<br>        while (iterator.hasNext()) {<br>            System.out.println(&quot;Fruit: &quot; + iterator.next());<br>        }<br>    }<br>}</pre><p>In this example, the Iterator inner class provides methods like hasNext() and next() to traverse the elements of the ArrayList sequentially. As an inner class, Iterator can directly access the private fields and methods of the ArrayList, such as its internal array storage and size, enabling efficient traversal without exposing these details to external code. This design maintains encapsulation while ensuring the ArrayList remains internally consistent during iteration, even if the collection is modified.</p><h4>Access Modifiers Allowed</h4><p>An inner class in Java can be private, public, protected, and package-private like another member.</p><p>💡 <strong>Tip</strong>: When defining a member class that doesn’t need access to its enclosing instance, always declare it as static to indicate it is independent of the outer class&#39;s instance.</p><h3>Static Inner Classes in Java</h3><p>Static nested classes are similar to static methods; they can be accessed without an instance of the outer class. Since they don’t have access to the instance variables of the outer class, they’re mainly used when the behavior of the nested class is independent of the outer class.</p><p>For example, the LinkedList class in Java contains a static Node class that represents each node in the linked list.</p><pre>public class LinkedList&lt;E&gt; {<br><br>  transient Node&lt;E&gt; first;<br><br>  transient Node&lt;E&gt; last;<br>  <br>  <br>  .......<br>  <br>  private static class Node&lt;E&gt; {<br>        E item;<br>        Node&lt;E&gt; next;<br>        Node&lt;E&gt; prev;<br><br>        Node(Node&lt;E&gt; prev, E element, Node&lt;E&gt; next) {<br>            this.item = element;<br>            this.next = next;<br>            this.prev = prev;<br>        }<br>    }<br><br>}</pre><p>Technically speaking, we should use static inner classes when the inner class does not need to access the members (variables or methods) of the outer class. A static inner class does not hold an implicit reference to an instance of the outer class. In other words, a static inner class serves as a helper to the outer class without relying on its instance.</p><h3>Comparison Between Inner Classes and Static Inner Classes</h3><p>Here’s a table that compares <strong>inner classes</strong> and <strong>static inner classes</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6snMD72BYg-jSQWC6FJj4A.png" /></figure><h3>Local Classes</h3><p>Local classes are nested classes defined within a method, accessible only within the scope of that method.</p><pre>public class OuterClass {<br>    public void calculate(int x) {<br>        // Local class within a method<br>        class LocalCalculator {<br>            public int square() {<br>                return x * x;<br>            }<br>        }<br>        LocalCalculator calculator = new LocalCalculator();<br>        System.out.println(&quot;Square is &quot; + calculator.square());<br>    }<br>}</pre><h4>Use Case</h4><p>They are used in methods where you need a one-time-use class to organize logic. They have access to final or effectively final variables of the enclosing method.</p><h4>Access Modifiers Allowed For Local Classes</h4><p>Local classes cannot have explicit access modifiers (same as local variables)</p><h3>Anonymous Inner Classes in Java</h3><p>Anonymous inner classes are local classes without a name, usually declared and instantiated at the same time. They’re commonly used for short-lived implementations, often for interfaces or abstract classes.</p><pre>interface Greeting {<br>    void sayHello();<br>}<br><br>public class OuterClass {<br>    public void createGreeting() {<br>        Greeting greeting = new Greeting() {<br>            @Override<br>            public void sayHello() {<br>                System.out.println(&quot;Hello from anonymous class!&quot;);<br>            }<br>        };<br>        greeting.sayHello();<br>    }<br>}</pre><h4>Access Modifiers Allowed</h4><p>Cannot have explicit access modifiers since they’re defined within a method or initializer block.</p><h3>Conclusion</h3><p>Nested classes in Java offer a structured way to encapsulate functionality within the context of another class. By understanding when and how to use each type, you can organize your code efficiently and leverage Java’s OOP capabilities effectively.</p><p><em>Originally published at </em><a href="https://javalaunchpad.com/nested-classes-in-java-a-comprehensive-guide/"><em>https://javalaunchpad.com</em></a><em> on November 23, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177a8069f8ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/nested-classes-in-java-a-comprehensive-guide-177a8069f8ce">Nested Classes in Java: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serialization and Deserialization in Java]]></title>
            <link>https://medium.com/javarevisited/serialization-and-deserialization-in-java-fbb9ece781d0?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb9ece781d0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[serialization]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 15:57:41 GMT</pubDate>
            <atom:updated>2024-12-09T12:43:30.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mge14urVgp1QhHvcR_10A.png" /><figcaption>serialization vs deserialization in java</figcaption></figure><p>Java Serialization and Deserialization enable us to convert objects into a <a href="https://www.scaler.com/topics/java/byte-stream-in-java/">byte stream</a> for storage or transmission, and later reconstruct them into their original form.</p><p>In this article, we’ll explore how Serialization and Deserialization work, how to implement them, and highlight best practices, potential pitfalls, and ways to leverage them in real-world applications.</p><h3>What are Serialization and Deserialization in Java?</h3><ul><li><strong>Serialization</strong>: The process of converting an object into a <a href="https://www.scaler.com/topics/java/byte-stream-in-java/">byte stream</a> so that it can be stored in a file, or sent over a network.</li><li><strong>Deserialization</strong>: The reverse process of converting a <a href="https://www.scaler.com/topics/java/byte-stream-in-java/">byte stream</a> back into a Java object.</li></ul><p>These mechanisms allow Java objects to be stored or transmitted in a format that can later be reconstructed, facilitating persistence when combined with storage solutions.</p><h3>How do you implement serialization and deserialization in Java?</h3><p>Serialization and Deserialization are straightforward with Java’s built-in APIs. At the core of this functionality is the Serializable interface, which we&#39;ll explore next.</p><h3>Serializable Interface in Java</h3><p>The Serializable interface is a marker interface in Java, meaning it does not contain any methods. Classes must implement Serializable to indicate that their instances can be serialized, While implementing Serializable allows a class to be serialized, all non-transient and non-static fields of the class must also be serializable. If any field references an object that does not implement Serializable, a <em>NotSerializableException </em>will be thrown.</p><p><strong>Example:</strong></p><pre>import java.io.Serializable;<br><br>public class Person implements Serializable {<br>    private String name;<br>    private int age;<br><br>    // Constructor, getters, and setters<br>}</pre><h3>Serializing an Object Using ObjectOutputStream</h3><p>Serialization is performed using the <em>ObjectOutputStream </em>class. Here&#39;s how to serialize an object:</p><pre>import java.io.FileOutputStream;<br>import java.io.ObjectOutputStream;<br><br>public class SerializationExample {<br>    public static void main(String[] args) {<br>        Person person = new Person(&quot;John Doe&quot;, 30);<br><br>        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(&quot;person.ser&quot;))) <br>        {<br>            oos.writeObject(person);<br>            System.out.println(&quot;Object serialized successfully.&quot;);<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>This code demonstrates how to serialize a Person object by converting it into a byte stream and saving it to a file named person.ser. The ObjectOutputStream is used for the serialization process, and the try-with-resources block ensures the stream is closed automatically.</p><h3>Deserializing an Object Using ObjectInputStream</h3><p>Deserialization uses the ObjectInputStream class to read the byte stream and reconstruct the object.</p><pre>import java.io.FileInputStream;<br>import java.io.ObjectInputStream;<br><br>public class DeserializationExample {<br>    public static void main(String[] args) {<br>        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(&quot;person.ser&quot;))) {<br>            Person person = (Person) ois.readObject();<br>            System.out.println(&quot;Deserialized Object: &quot; + person.getName());<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>This code illustrates the deserialization process, where a previously serialized Person object is read from the file person.ser and reconstructed in memory. The ObjectInputStream is used to read the object, and the try-with-resources block ensures the stream is properly closed.</p><h3>What is a serialVersionUID and why should I use it?</h3><p>The <strong>serialVersionUID</strong> is a unique identifier used during the serialization and deserialization of Java objects to verify compatibility between the sender and receiver of a serialized object. If a class is modified (e.g., by adding or removing fields) after serialization, and the serialVersionUID has not been explicitly defined, the JVM generates one based on the class structure. This can lead to a mismatch if the class changes, resulting in a <strong>InvalidClassException</strong> during deserialization. By explicitly declaring a serialVersionUID, developers can control this versioning process and ensure compatibility.</p><p>For example, consider a class without a defined serialVersionUID:</p><pre>public class Book implements Serializable {<br><br>    private String name;<br>    private String author;<br>    private double price;<br>    <br>    // getters , setters , constructors<br>}</pre><p>If we serialize this class and later modify it (e.g., by adding a new field), deserializing the older serialized object throws an exception.</p><pre>java.io.InvalidClassException: Book; local class incompatible: stream classdesc serialVersionUID = -2892936963561990304, local class serialVersionUID = 7474211501842758058</pre><p>To avoid this, explicitly define serialVersionUID in the class:</p><pre>public class Book implements Serializable {<br>    private static final long serialVersionUID = 1L; <br>    private String name;<br>    private String author;<br>    private double price;<br>    // getters , setters , constructors<br>}</pre><p>This approach ensures controlled serialization behavior, even if the class evolves.</p><p><strong>Note:</strong> Keep in mind that when we add or remove a field, the JVM reconstructs the object based on the old version of the serialized class. When we add a new field, it takes its default value, and when we remove a field, the system ignores it even if it exists in the serialized stream.</p><h3>Deserialization in Java step-by-step</h3><p>The JVM starts by reading the serialized data stream, which contains metadata about the serialized object. This includes the class name, serialVersionUID, and the sequence of fields and values.</p><p>The JVM checks the serialVersionUID in the stream against the serialVersionUID of the current class in memory:</p><ul><li>If they differ, a java.io.InvalidClassException is thrown, as the class definitions are deemed incompatible.</li><li>If they match, the JVM proceeds with deserialization.</li></ul><p>The JVM allocates memory for a new instance of the class but does not call the class’s constructors. This is because constructors might modify fields, and the goal of deserialization is to reconstruct the object state exactly as it was.</p><p>The JVM reads the field values from the serialized stream in the order they were written during serialization:</p><ul><li><strong>Existing Fields</strong>: For fields present in both the serialized stream and the current class, we directly assign their values.</li><li><strong>Added Fields</strong>: If we add a field to the current class that doesn’t exist in the serialized stream (e.g., a new field added after serialization), we assign it its default value (e.g., null for objects, 0 for integers, false for booleans).</li><li><strong>Removed Fields</strong>: If we remove a field from the current class but it still exists in the serialized stream (e.g., a field removed after serialization), we ignore its data in the stream.</li></ul><h3>Transient and Static Fields During Serialization</h3><h3>What is the transient Keyword?</h3><p>The transient keyword marks a field to be excluded from serialization, meaning its value will not be included in the byte stream during the serialization process.</p><h4>Why Static and Transient Fields Are Not Serialized?</h4><p><strong>Example:</strong></p><pre>import java.io.Serializable;<br><br>public class Employee implements Serializable {<br>    private static final long serialVersionUID = 1L;<br>    private String name;<br>    private transient String password;<br><br>    // Constructor, getters, and setters<br>}</pre><h3>Conclusion</h3><p>Serialization and Deserialization are indispensable tools for Java developers, enabling object persistence and data transfer. By implementing the Serializable interface and understanding key concepts like transient fields and constructors, you can avoid common pitfalls and make your Java applications more robust.</p><p><em>Originally published at </em><a href="https://javalaunchpad.com/serialization-and-deserialization-in-java/"><em>https://javalaunchpad.com</em></a><em> on November 23, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb9ece781d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/serialization-and-deserialization-in-java-fbb9ece781d0">Serialization and Deserialization in Java</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 3: Implementing JWT Authentication with Keycloak]]></title>
            <link>https://medium.com/javarevisited/spring-boot-3-implementing-jwt-authentication-with-keycloak-a1dae49c18ae?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1dae49c18ae</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 18:05:20 GMT</pubDate>
            <atom:updated>2024-08-18T15:03:10.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>With the release of Spring Boot 3, many developers have encountered challenges integrating Keycloak due to the deprecation of the WebSecurityConfigurerAdapter. This change disrupted the previously seamless integration with Keycloak’s adapters, specifically because KeycloakWebSecurityConfigurerAdapter it extends WebSecurityConfigurerAdapter. Without these adapters, integrating Keycloak with Spring Boot 3 may seem daunting, but there are effective alternatives available.</p><h3>2. Keycloak as an Authorization Server</h3><p>To address these integration challenges, a practical solution is to configure your Spring Boot application as a Resource Server. This configuration allows your application to manage and secure APIs by validating requests against an authorization server — Keycloak in this case. When a request reaches your application, it intercepts the request, extracts the JWT token, and communicates with Keycloak to validate the token.</p><blockquote>Keycloak acts as the Authorization Server responsible for issuing JWT tokens to clients attempting to access protected resources. Typically, a front-end application retrieves a JWT token from Keycloak and includes it in requests to secured APIs.</blockquote><p>To facilitate this integration, Spring Boot provides the spring-boot-starter-security-oauth2-resource-server starter. This starter automates much of the configuration needed to enable JWT-based authentication, allowing your application to easily communicate with Keycloak for token validation. The following sections will break down the key steps involved in this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hovheILYHKLbNgRR4ioJbg.png" /></figure><h3>3. Authentication Workflow</h3><p>When a user sends a request to a protected resource within your Spring Boot application, the request includes a JWT token provided by Keycloak. The authentication process follows these steps:</p><ol><li><strong>Intercepting the Request:</strong> The BearerTokenAuthenticationFilter intercepts incoming requests, extracts the JWT token, and creates a BearerAuthenticationToken object.</li><li><strong>Authentication Management:</strong> The AuthenticationManager (typically implemented by ProviderManager) is invoked to authenticate the token. It searches for an AuthenticationProvider that supports the provided authentication object. In this case, the JWTAuthenticationProvider is selected.</li><li><strong>Token Validation:</strong> The selected AuthenticationProvider decodes the JWT token into a JWT object and verifies its validity using JWTDecoder. If the token is valid, it is converted into an AbstractAuthenticationToken by JWTAuthenticationConverter and stored in the SecurityContextHolder.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owJfecG2ZrGDj375OFux1w.png" /><figcaption>Authentication Workflow</figcaption></figure><p>The code snippet below illustrates part of this process within the BearerTokenAuthenticationFilter:</p><pre>String token;<br>  try {<br>   token = this.bearerTokenResolver.resolve(request);<br>  }<br>  catch (OAuth2AuthenticationException invalid) {<br>   this.logger.trace(&quot;Sending to authentication entry point since failed to resolve bearer token&quot;, invalid);<br>   this.authenticationEntryPoint.commence(request, response, invalid);<br>   return;<br>  }<br>  if (token == null) {<br>   this.logger.trace(&quot;Did not process request since did not find bearer token&quot;);<br>   filterChain.doFilter(request, response);<br>   return;<br>  }<br><br>  BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken(token);<br>  authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));<br><br>  try {<br>   AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request);<br>   Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest);<br>   SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();<br>   context.setAuthentication(authenticationResult);<br>   this.securityContextHolderStrategy.setContext(context);<br>   this.securityContextRepository.saveContext(context, request, response);<br>   if (this.logger.isDebugEnabled()) {<br>    this.logger.debug(LogMessage.format(&quot;Set SecurityContextHolder to %s&quot;, authenticationResult));<br>   }<br>   filterChain.doFilter(request, response);<br>  }<br>  catch (AuthenticationException failed) {<br>   this.securityContextHolderStrategy.clearContext();<br>   this.logger.trace(&quot;Failed to process authentication request&quot;, failed);<br>   this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed);<br>  }</pre><h3>4. Security Configuration &amp; Project Setup</h3><p>With a theoretical understanding of the process, it’s time to dive into implementation. Before proceeding, ensure you have:</p><ul><li>Java 17 installed</li><li>Keycloak is up and running with a public client, roles, and users configured</li><li>A Spring Boot 3 project is set up and ready</li></ul><h4>4.1. Authorization Server ( Keycloak ) Setup</h4><p>Before proceeding, ensure your Keycloak server is properly configured. Set up a public client for token retrieval and create your testing user.</p><h4><strong>4.2. Token Retrieval</strong></h4><p>For testing purposes, we’ll use Postman to retrieve a token from Keycloak. If you have an SPA (Single Page Application) that handles this, feel free to use it instead.</p><p>To obtain a token for a specific user, you can use the /token endpoint provided by Keycloak: http://localhost:8180/realms/master/protocol/openid-connect/token. If you&#39;re using a custom realm, replace &quot;master&quot; with the name of your realm, and ensure you adjust the host and port according to your Keycloak setup.</p><p>This endpoint requires four parameters: the username and password of the user, the grant_type (which we&#39;ll set to &quot;password&quot;), and the client_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjXTQYyK_i8SC_kSubQ_dQ.png" /><figcaption>token retrieval from keycloak</figcaption></figure><blockquote>Ensure you include this token in the Authorization header when making requests to your backend application.</blockquote><h4>4.3. Resource Server Setup</h4><p>Our Spring Boot application will function as a Resource Server, meaning it will protect its resources (endpoints) and only allow access to them if the JWT token provided by the client is valid. Let’s get started with the setup!</p><h4>Maven Dependencies</h4><p>For our project, we need to include the spring-boot-starter-oauth2-resource-server dependency, which will bring in all the necessary components to handle JWT authentication.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-oauth2-resource-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>Application Properties</h4><p>The default security configuration in Spring Boot 3 has been greatly simplified, thanks to the enhancements in the Spring Security framework. By simply adding the spring-boot-starter-oauth2-resource-server dependency, Spring Boot auto-configures the necessary components to handle JWT tokens. all what we need is to specify some properties in the application.properties or application.yml file.</p><p>Here’s an example configuration:</p><pre>spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8180/realms/master<br>spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:8180/realms/master/protocol/openid-connect/certs</pre><p>In this setup:</p><ul><li><strong>issuer-uri</strong>: This is the unique identifier of your Keycloak realm, representing the issuer of the JWT tokens.</li><li><strong>jwk-set-uri</strong>: This points to the endpoint where Keycloak exposes its JSON Web Key Set (JWKS), used to verify the signatures of the JWT tokens.</li></ul><h4>Custom Configuration</h4><p>You can still tailor the security configuration to meet your application’s specific requirements. Below is an example of a custom security configuration class:</p><pre>@EnableWebSecurity<br>@Configuration<br>public class SecurityConfig {<br>    <br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        <br>        // Disable CSRF protection<br>        http.csrf(AbstractHttpConfigurer::disable);<br>        <br>        // Configure CORS settings<br>        http.cors(cors -&gt; cors.configurationSource(request -&gt; corsConfiguration));<br>        <br>        // Require authentication for all requests<br>        http.authorizeHttpRequests(request -&gt; request.anyRequest().authenticated());<br>        <br>        // Set session management to stateless<br>        http.sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br>        <br>        // Customize OAuth2 resource server configuration<br>        http.oauth2ResourceServer(<br>            oauth2 -&gt; {<br>                // Add custom JWT decoder, converter, or other configurations<br>            }<br>        );<br>        <br>        return http.build();<br>    }<br>}</pre><p>This setup provides a foundation for customizing your security configuration while still allowing for further adjustments as needed.</p><h3>5. Conclusion</h3><p>While the transition away from WebSecurityConfigurerAdapter in Spring Boot 3 might appear daunting at first, the enhanced flexibility and modular approach ultimately lead to a more streamlined and powerful integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1dae49c18ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-boot-3-implementing-jwt-authentication-with-keycloak-a1dae49c18ae">Spring Boot 3: Implementing JWT Authentication with Keycloak</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effective Relationship Mapping with Hibernate & JPA: @OneToMany]]></title>
            <link>https://medium.com/javarevisited/effective-relationship-mapping-with-hibernate-jpa-onetomany-c80324a94e53?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80324a94e53</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 14:37:59 GMT</pubDate>
            <atom:updated>2024-01-14T10:32:32.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AL3NIX3psOuOsRfI" /><figcaption>Photo by <a href="https://unsplash.com/@_mansigujarathi25_?utm_source=medium&amp;utm_medium=referral">Mansi Gujarathi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Introduction</h3><p>Establishing entity relationships using <em>JPA</em> and <em>Hibernate</em> is relatively straightforward; anyone can work with annotations like <em>@OneToOne</em>, <em>@OneToMany</em>, and <em>@ManyToMany</em> to achieve the desired results. However, it’s crucial to consider performance implications. Relationship mapping can be a double-edged sword, requiring careful attention.</p><p>In this article, we will explore an example of the <em>@OneToMany</em> and <em>@ManyToOne</em> relationship, discussing various techniques. We’ll begin with the basics and progressively enhance the mapping until we achieve the best mapping.</p><h3><em>2. Sources of Inspiration</em></h3><p>When writing this comprehensive guide to mastering the relationship mapping using <strong><em>hibarnate and JPA</em></strong> , this resources was my source of inspiration and the main source of knowledge.</p><p>📘 <a href="https://vladmihalceastore.teachable.com/p/high-performance-java-persistence-ebook?affcode=1748817_usnonpfd"><em>High-Performance Java Persistence Book</em></a>: Authored by <em>Vlad Mihalcea</em>, this book stands as a cornerstone for understanding the best practices in designing and optimizing data access layers.</p><p>🎓 <a href="https://vladmihalceastore.teachable.com/p/high-performance-java-persistence-online?affcode=1748817_usnonpfd"><em>High-Performance Java Persistence Video Course</em></a>: For those who prefer a dynamic learning experience, Vlad’s video course offers practical insights into achieving optimal performance in Java applications.</p><h3>3. Uniderictional @OneToMany</h3><p>In this article, we will use the example of a Student and Address, assuming that a student can have multiple addresses, and each address belongs exclusively to one student.</p><blockquote>Student.jva</blockquote><pre>@Entity<br>@Getter<br>@Setter<br>@ToString<br>public class Student {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br><br>    private String name;<br>    private int age;<br>    private String mobile;<br><br>}</pre><blockquote>Address.java</blockquote><pre>@Entity<br>@Getter<br>@Setter<br>public class Address {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String city;<br>    private String zipCode;<br><br>}</pre><h4>3.1. Relationship mapping using a Join Table</h4><p>To establish a unidirectional relationship between student &amp; address entities, typically, we add the following line to the Student class.</p><pre>@OneToMany<br>private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();</pre><p>When utilizing <em>@OneToMany</em> without additional configuration, Hibernate seamlessly generates a<em> join table</em> to meticulously manage the relationship, effectively tracking the association between students and their respective addresses. The name of this join table would be STUDENT_ADDRESS (PARENT_CHILD).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*9QFP-2f2pR0FP_8pljayGQ.png" /></figure><p>In the next step, we will save some students to the <em>database</em>. Additionally, we will set the ‘<em>show_sql</em>’ <em>Hibernate</em> property to view the SQL queries generated by Hibernate. This will allow us to analyze the number of queries <em>Hibernate</em> generates with different mappings techniques.</p><pre>        Student student = new Student();<br>        student.setName(&quot;John&quot;);<br>        student.setAge(20);<br>        student.setMobile(&quot;1234567890&quot;);<br><br>         // address1<br>        Address address1 = new Address();<br>        address1.setCity(&quot;Marrakech&quot;);<br>        address1.setZipCode(&quot;34226&quot;);<br><br>        //  address2<br>        Address address2 = new Address();<br>        address2.setCity(&quot;Casablanca&quot;);<br>        address2.setZipCode(&quot;43563&quot;);<br><br>        // address3<br>        Address address3 = new Address();<br>        address3.setCity(&quot;Rabat&quot;);<br>        address3.setZipCode(&quot;23512&quot;);<br><br>        student.getAddresses().add(address1);<br>        student.getAddresses().add(address2);<br>        student.getAddresses().add(address3);<br>        // save student object<br>        studentRepository.save(student);</pre><p>If we run directly this code, we will encounter the following <strong><em>TransientObjectException: ‘object references an unsaved transient instance — save the transient instance before flushing.’ </em></strong>This issue arises because the Address objects are not saved yet. We have two choices here. The first is to save them before saving the Student object, and the second one is to use <em>cascading</em>. I will go with the second choice.</p><pre>@OneToMany(cascade = CascadeType.ALL)<br>private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();</pre><p>Here are the <em>SQL</em> queries generated by <em>Hibernate</em> for us :</p><pre>Hibernate: insert into student (age,mobile,name,id) values (?,?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: insert into student_addresses (student_id,addresses_id) values (?,?)<br>Hibernate: insert into student_addresses (student_id,addresses_id) values (?,?)<br>Hibernate: insert into student_addresses (student_id,addresses_id) values (?,?)</pre><p>7 queries needed to insert a student and his 3 addresses, the first 4 queries save the objects, while the last 3 are solely for establishing the relationship by inserting into the join table. To optimize this process, let’s explore an alternative method that can help us avoid the last 3 queries. This implies seeking a way to establish the relationship without relying on a join table.</p><h4>3.2. Relationship mapping using a Foreign Key</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xm3atbvBT1Ishu1rD5Wb4g.png" /></figure><p>If we examine the previous technique that <em>Hibernate</em> used to configure the relationship, we might find it a bit wierd. Using a<em> join table</em> is typically useful when dealing with a <em>many-to-many relationship</em>. Additionally, since an address should belong exclusively to one student, the address_id column in both the address and student_address join table will be the same. Let’s merge the join table with the address table based on the address_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NrOa4GvGUfup67SZsrsUw.png" /></figure><p>Erase one of the replicated address_id entries and arrange the student_id to be the last column in the table, resulting in something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEulZe7iffMJvfcMBlYfZA.png" /></figure><p>Finally, our relationship is established using the student_id in the address table, serving as our <em>foreign key</em>. To achieve this using <em>Hibernate</em>, simply add the <em>@JoinColumn</em> annotation as follows:</p><pre>@OneToMany(cascade = CascadeType.ALL)<br>@JoinColumn(name = &quot;student_id&quot;)<br>private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();</pre><p>This method will generate exactly the same number of queries, but with some changes. Instead of generating SQL queries that save the mapping inside the <em>join table</em>, <em>Hibernate</em> will now only raise an update query to set the student_id in every persisted address. While for <em>us</em>, it’s still 7 queries, I know we will reduce the number in the next section!</p><pre>Hibernate: insert into student (age,mobile,name,id) values (?,?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: insert into address (city,zip_code,id) values (?,?,default)<br>Hibernate: update address set student_id=? where id=?<br>Hibernate: update address set student_id=? where id=?<br>Hibernate: update address set student_id=? where id=?</pre><h3>4. Biderictional @OneToMany</h3><p>Establishing a <em>biderictional relationship</em> means that the Parent has the list of it’s childs and also the child can access it’s parent let’s update our code to support a <em>biderictional relationship.</em></p><blockquote>Student.java</blockquote><pre>@Entity<br>@Getter<br>@Setter<br>@ToString<br>public class Student {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br><br>    private String name;<br>    private int age;<br>    private String mobile;<br><br>    @OneToMany(cascade = CascadeType.ALL , mappedBy = &quot;student&quot;)<br>    private List&lt;Address&gt; addresses = new ArrayList&lt;&gt;();<br><br>}</pre><blockquote>Address.java</blockquote><pre>@Entity<br>@Getter<br>@Setter<br>public class Address {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String city;<br>    private String zipCode;<br><br><br>    @ManyToOne<br>    private Student student;<br><br>}</pre><p>The mappedBy attribute informs <em>Hibernate</em> that the relationship is mapped by an attribute called ‘student’ in the Address table. <em>Hibernate</em> will perform the following operation: create a foreign key in the Address table named ‘student_id,’ assuming the primary key in the Student class called ‘id’.</p><p>let’s save some objects now :</p><pre>        Student student = new Student();<br>        student.setName(&quot;John&quot;);<br>        student.setAge(20);<br>        student.setMobile(&quot;1234567890&quot;);<br><br>        Address address1 = new Address();<br>        address1.setCity(&quot;Marrakech&quot;);<br>        address1.setZipCode(&quot;34226&quot;);<br>        address1.setStudent(student);<br><br>        Address address2 = new Address();<br>        address2.setCity(&quot;Casablanca&quot;);<br>        address2.setZipCode(&quot;43563&quot;);<br>        address2.setStudent(student);<br><br>        Address address3 = new Address();<br>        address3.setCity(&quot;Rabat&quot;);<br>        address3.setZipCode(&quot;23512&quot;);<br>        address3.setStudent(student);<br><br>        student.getAddresses().add(address1);<br>        student.getAddresses().add(address2);<br>        student.getAddresses().add(address3);<br><br>        studentRepository.save(student);</pre><p>At this moment here are the queries used to save the student with it’s adresses</p><pre>Hibernate: insert into student (age,mobile,name,id) values (?,?,?,default)<br>Hibernate: insert into address (city,student_id,zip_code,id) values (?,?,?,default)<br>Hibernate: insert into address (city,student_id,zip_code,id) values (?,?,?,default)<br>Hibernate: insert into address (city,student_id,zip_code,id) values (?,?,?,default</pre><p>Only 4 queries are generated when we use <em>bidirectional relationships</em>. This is because, when <em>Hibernate</em> attempts to persist the Address object, it already has the associated Student parent object. Consequently, it’s straightforward to include the student_id with the request, eliminating the need for an additional update query.</p><blockquote>Consider using a <em>bidirectional relationship</em> even if you navigate from just one side and don’t require access to the other. As we’ve seen, bidirectional relationships help Hibernate optimize the generated queries.</blockquote><p>But what if the list in the parent objects has a significant number of elements? This could potentially lead to performance issues (although it’s not a common occurrence in real-life projects, it’s crucial to be aware of it). Let’s delve into this question in the next section.</p><h3>5. One-to-Many Relationships Solely with @ManyToOne Annotation</h3><blockquote>Let’s establish a consistent vocabulary for this paragraph. When I refer to the term ‘Parent,’ I mean the side that possesses the list of child elements. In our case, the ‘Student’ is the parent because it holds the list of addresses. Conversely, the ‘Child’ is the side that contains the foreign key in our address entity.</blockquote><p>Consider a scenario where a parent object has a substantial list of child elements. Loading the entire collection into memory at once can result in increased memory usage and longer response times. To mitigate this, it’s advisable not to grant <em>Hibernate</em> full control over this list. Instead, we should take charge of managing it ourselves, utilizing techniques such as pagination to prevent loading the entire list.</p><ul><li>Address.java</li></ul><pre>public class Address {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String city;<br>    private String zipCode;<br><br><br>    @ManyToOne<br>    private Student student;<br><br>}</pre><ul><li>Student.java</li></ul><pre>public class Student {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br><br>    private String name;<br>    private int age;<br>    private String mobile;<br><br>}</pre><p>In this case, you can create a method in your repository to fetch paginated addresses for a given student ID:</p><pre>public interface AddressRepository extends JpaRepository&lt;Address, Long&gt; {<br>    Page&lt;Address&gt; findByStudentId(Long studentId, Pageable pageable);<br>}</pre><p>This way, when you fetch a student’s addresses, only the required subset of addresses will be loaded into memory, improving performance and reducing the risk of memory-related issues with a large number of addresses.</p><p>We come to the end of our article, If you have any questions or insights to share, <strong><em>please feel free to leave them in the comment section below</em></strong>. I’ll be delighted to respond and further discuss any aspects you’d like to explore.</p><p><strong>If you’re passionate about enhancing your knowledge of the persistence layer with Hibernate, I highly recommend delving into the invaluable resources curated by Vlad Mihalcea, the esteemed author of the ‘</strong><a href="https://vladmihalceastore.teachable.com/p/high-performance-java-persistence-ebook?affcode=1748817_usnonpfd"><strong>High-Performance Java Persistence</strong></a><strong>’ book. This comprehensive guide explores the best practices for designing and optimizing data access layers in Java applications. For a more immersive learning experience, don’t miss out on Vlad’s outstanding video course, ‘</strong><a href="https://vladmihalceastore.teachable.com/p/high-performance-java-persistence-online?affcode=1748817_usnonpfd"><strong>High-Performance Java Persistence video Edition</strong></a><strong>’ .</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80324a94e53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/effective-relationship-mapping-with-hibernate-jpa-onetomany-c80324a94e53">Effective Relationship Mapping with Hibernate &amp; JPA: @OneToMany</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring MVC Part 4:Custom Validation Annotations]]></title>
            <link>https://medium.com/javarevisited/spring-mvc-part-4-custom-validation-annotations-16d3da88915?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/16d3da88915</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 01:03:32 GMT</pubDate>
            <atom:updated>2024-05-29T20:27:55.028Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a Custom Validation Annotation from Scratch in Spring MVC!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MAGvqIt46sUXFbn8" /></figure><blockquote>Explore my latest article series on <a href="https://javalaunchpad.com/">JavaLaunchpad</a>, where you’ll find in-depth knowledge and practical examples covering a wide range of components and features in Spring MVC.</blockquote><blockquote><a href="https://javalaunchpad.com/introduction-to-spring-mvc-architecture/">1- Spring MVC Architecture</a></blockquote><blockquote><a href="https://javalaunchpad.com/dispatcherservlet-configuration/">2- The 3 Ways to Configure DispatcherServlet In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/most-popular-spring-mvc-annotations/">3- Most Popular Spring MVC Annotations</a></blockquote><blockquote><a href="https://javalaunchpad.com/data-binding/">4- Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/spring-mvc-handlerinterceptor/">5- How to Use HandlerInterceptor In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/customizing-data-binding-in-spring-mvc-creating-your-own-formatter/">6- Customizing Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/understanding-the-difference-between-handler-interceptors-and-filters-in-spring-mvc/">7- HandlerInterceptor VS. Filter</a></blockquote><h3>1. Introduction</h3><p>In this article, we will explore how to develop a custom validator in Spring MVC. This validator will be implemented as an annotation, similar to the validation constraints provided by the Bean Validation API, which we discussed in our previous article,<a href="https://medium.com/javarevisited/spring-mvc-part3-bean-validation-ee81c6a8182"> Spring MVC Part3</a>.</p><p>To delve further into this topic, it is essential to have a basic understanding of annotations in Java. If you are interested, I recommend reading the book <a href="https://amzn.to/3JPCZfM">Core Java: Advanced Features, Volume 2 by Cay S. Horstmann</a>.</p><h3>2. Analyzing @Size Validation Constraint</h3><p>To gain a deeper understanding of the validation constraints in Spring MVC, let’s begin by analyzing one specific implementation: the pre-built @Size constraint. This constraint allows us to validate the size of a field or property.</p><p>To examine its implementation, let’s take a look at the source code of the @Size validator.</p><pre>@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})<br>@Retention(RetentionPolicy.RUNTIME)<br>@Repeatable(List.class)<br>@Documented<br>@Constraint(<br>    validatedBy = {}<br>)<br>public @interface Size {<br>    String message() default &quot;{javax.validation.constraints.Size.message}&quot;;<br><br>    Class&lt;?&gt;[] groups() default {};<br><br>    Class&lt;? extends Payload&gt;[] payload() default {};<br><br>    int min() default 0;<br><br>    int max() default Integer.MAX_VALUE;<br><br>    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})<br>    @Retention(RetentionPolicy.RUNTIME)<br>    @Documented<br>    public @interface List {<br>        Size[] value();<br>    }<br>}</pre><p>Let’s break down the annotation line by line and work towards building our own custom annotation:</p><blockquote>@<strong>interface</strong> keyword</blockquote><p>An annotation is defined using the @interface keyword, followed by the name of the annotation. For example:</p><pre>@interface MyAnnotation {<br>}</pre><p>An annotation can have elements, similar to a class, which are called annotation members. These members are defined by methods inside the annotation. For example, the following defines an annotation with a single member called “value”:</p><pre>@interface MyAnnotation {<br>  int value();<br>}</pre><p>Annotations can be applied to various parts of a Java program, such as classes, methods, variables, and even other annotations. They can be used to provide meta-data for the Java compiler, Java runtime, or for any tool that processes Java code.</p><p>You can also annotate an annotation with other annotations, this is called meta-annotation.</p><blockquote><strong>@<em>Target</em></strong> Annotation</blockquote><p>The @Target annotation is used in Java annotations to specify the elements to which the annotation can be applied. It allows us to define the target types, such as classes, fields, methods, etc., where the annotation can be used. By using the @Target annotation, we can restrict the usage of our annotation to specific elements, ensuring that it is applied only where it makes sense and providing more control over its usage.</p><p>For example, if we create a custom annotation that is meant to be applied only to fields, we can use @Target(ElementType.FIELD) to enforce this restriction. This way, if someone tries to apply our annotation to a method or a class, it will result in a compilation error.</p><p>The @Target annotation takes a single argument, which is an enumeration of ElementType constants like :</p><ul><li>ElementType.ANNOTATION_TYPE : can be used on an annotation type.</li><li>ElementType.CONSTRUCTOR : can be used on a constructor.</li><li>ElementType.FIELD : can be used on a field or property.</li><li>ElementType.METHOD : can be used on a method.</li></ul><p>In our example, @Size is annotated with</p><pre>@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})</pre><p>which means that this annotation can be used on methods, fields, annotation types, constructors, parameters and type uses.</p><blockquote><strong><em>@Retention </em></strong>Annotation</blockquote><p>The @Retention annotation controls the lifespan of an annotation. It is used to specify when an annotation should be available to the JVM. There are three possible values for the RetentionPolicy:</p><ul><li>SOURCE: The annotation will be retained only in the source code and will be discarded by the compiler. It is not available at runtime.</li><li>CLASS: The annotation will be retained by the compiler and included in the class file, but it will not be available at runtime. This is the default retention policy.</li><li>RUNTIME: The annotation will be retained by the compiler and included in the class file and it will be available at runtime via the Reflection API.</li></ul><p>In our example, @Size is annotated with</p><pre>@Retention(RetentionPolicy.RUNTIME)</pre><p>which means that this annotation will be available at runtime via the Reflection API.</p><blockquote><strong>@Constraint</strong></blockquote><p>When using the @Constraint annotation, we should provide an implementation class that specifies the validation logic for the custom constraint. This implementation class should implement the ConstraintValidator interface provided by the Bean Validation API.</p><p>The @Constraint annotation requires the <strong>validatedBy </strong>attribute This parameter specifies the class that implement the ConstraintValidator interface and provide the validation logic for the custom constraint.</p><p>For example, let’s say we have a custom constraint named @MyConstraint, and you have an implementation class named MyConstraintValidator that implements ConstraintValidator&lt;MyConstraint, Object&gt;. You would specify it as follows:</p><pre>@Constraint(validatedBy = MyConstraintValidator.class)<br>public @interface MyConstraint {<br>    // ...<br>}</pre><p>It’s important to note that the ConstraintValidator interface requires two type parameters: the custom constraint annotation type (MyConstraint in the example) and the type of the element being validated (Object in the example). These type parameters define the association between the constraint and its validator.</p><h3>3. Implementing Custom Validation: Creating @MultipleOfFive Constraint Step by Step</h3><p>To follow along with me, please start by creating a Spring Boot project or pull the source code associated with this article from <a href="https://github.com/hamzanassour/Spring-MVC-Examples">GitHub</a>.</p><p>Let’s start by developing the annotation first. We will build a simple one called @MultipleOfFive annotation. This annotation will be used to check whether an integer is a multiple of five or not.</p><ul><li><strong>@MultipleOfFive Annotation</strong></li></ul><pre>import jakarta.validation.Constraint;<br>import jakarta.validation.Payload;<br><br>import java.lang.annotation.ElementType;<br>import java.lang.annotation.Retention;<br>import java.lang.annotation.RetentionPolicy;<br>import java.lang.annotation.Target;<br><br>@Target(ElementType.FIELD)<br>@Retention(RetentionPolicy.RUNTIME)<br>@Constraint(validatedBy = MultipleOfFiveValidator.class )<br>public @interface MultipleOfFive {<br>    String message() default &quot;The number provided is not a multiple of 5. Please try again.&quot;;<br>    Class&lt;?&gt;[] groups() default { };<br>    Class&lt;? extends Payload&gt;[] payload() default { };<br>}</pre><ul><li><strong>MultipleOfFiveValidator Class</strong></li></ul><p>As mentioned earlier in this article, the validation logic should be implemented within a class that implements the ConstraintValidator interface provided by the Bean Validation API.</p><pre>import jakarta.validation.ConstraintValidator;<br>import jakarta.validation.ConstraintValidatorContext;<br><br><br>public class MultipleOfFiveValidator implements ConstraintValidator&lt;MultipleOfFive , Integer&gt;{<br>    @Override<br>    public void initialize(MultipleOfFive constraintAnnotation) {<br>    }<br><br>    @Override<br>    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {<br>        return integer %5 == 0;<br>    }<br>}</pre><p>In this MultipleOfFiveValidator class:</p><ul><li>We implement the ConstraintValidator&lt;MultipleOfFive, Integer&gt; interface, where MultipleOfFive refers to our custom annotation, and Integer represents the type of field being validated (in this case, an integer).</li><li>The initialize method is called during initialization of the validator, but since we don&#39;t need any custom initialization, it&#39;s left empty.</li><li>The isValid method contains the validation logic. It checks if the provided value is divisible by 5 (i.e., a multiple of 5) and returns true if valid, or false otherwise.</li></ul><h3>4. Demo</h3><p>For demonstration purposes, I have created a simple REST API along with a DTO (Data Transfer Object) that we will be validating.</p><ul><li><strong>EmployeeRequest</strong></li></ul><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class EmployeeRequest {<br><br>    private String name ;<br><br>    @MultipleOfFive<br>    private int age ;<br><br>}</pre><ul><li><strong>EmployeeController</strong></li></ul><pre>@RestController<br>@RequestMapping(&quot;/api/employees&quot;)<br>public class EmployeeController {<br><br>    @PostMapping(&quot;&quot;)<br>    public ResponseEntity&lt;String&gt; saveEmployee(@Valid @RequestBody EmployeeRequest employeeRequest, BindingResult bindingResult) {<br>        if (bindingResult.hasErrors()) {<br>            List&lt;String&gt; errorMessages = bindingResult.getAllErrors().stream()<br>                    .map(ObjectError::getDefaultMessage)<br>                    .collect(Collectors.toList());<br><br>            return ResponseEntity.badRequest().body(String.join(&quot; &quot;, errorMessages));<br>        }<br><br>        // Save the employee<br>        // ...<br><br>        return ResponseEntity.ok(&quot;Employee saved successfully&quot;);<br>    }<br>}</pre><p>Our REST controller (EmployeeController ) handles a POST request for saving an employee. The method save() takes an EmployeeRequest object in the request body, performs validation using @Valid annotation, and collects any validation errors using BindingResult. The method then builds a string with the error messages and returns it as the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T5nUn0wdVUrHsYknkqrpng.png" /><figcaption>no validation error</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dV-oNFi3cQIvNr0I6fTRpw.png" /><figcaption>validation error</figcaption></figure><h3>5. Unit Tests</h3><pre>import org.junit.jupiter.api.Test;<br>import static org.junit.jupiter.api.Assertions.assertFalse;<br>import static org.junit.jupiter.api.Assertions.assertTrue;<br>import static org.mockito.Mockito.*;<br><br>@SpringBootTest<br>class MultipleOfFiveValidatorTests {<br><br><br>        @Test<br>        public void testValidValue() {<br>            MultipleOfFiveValidator validator = new MultipleOfFiveValidator();<br>            assertTrue(validator.isValid(10, null));<br>            assertTrue(validator.isValid(0, null));<br>            assertTrue(validator.isValid(-15, null));<br>        }<br><br>        @Test<br>        public void testInvalidValue() {<br>            MultipleOfFiveValidator validator = new MultipleOfFiveValidator();<br>            assertFalse(validator.isValid(7, null));<br>            assertFalse(validator.isValid(18, null));<br>            assertFalse(validator.isValid(-9, null));<br>        }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16d3da88915" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/spring-mvc-part-4-custom-validation-annotations-16d3da88915">Spring MVC Part 4:Custom Validation Annotations</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Profiles: Step-by-Step Guide for Developers]]></title>
            <link>https://medium.com/javarevisited/getting-started-with-spring-boot-profiles-1e00159f0542?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e00159f0542</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 15:39:57 GMT</pubDate>
            <atom:updated>2024-11-23T16:43:23.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring how to manage different environments and configurations for your applications.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q-S0qqGh59vMajUm" /></figure><blockquote>Explore my latest article series on <a href="https://javalaunchpad.com/">JavaLaunchpad</a>, where you’ll find in-depth knowledge and practical examples covering a wide range of components and features in Spring MVC.</blockquote><blockquote><a href="https://javalaunchpad.com/introduction-to-spring-mvc-architecture/">1- Spring MVC Architecture</a></blockquote><blockquote><a href="https://javalaunchpad.com/dispatcherservlet-configuration/">2- The 3 Ways to Configure DispatcherServlet In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/most-popular-spring-mvc-annotations/">3- Most Popular Spring MVC Annotations</a></blockquote><blockquote><a href="https://javalaunchpad.com/data-binding/">4- Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/spring-mvc-handlerinterceptor/">5- How to Use HandlerInterceptor In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/customizing-data-binding-in-spring-mvc-creating-your-own-formatter/">6- Customizing Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/understanding-the-difference-between-handler-interceptors-and-filters-in-spring-mvc/">7- HandlerInterceptor VS. Filter</a></blockquote><blockquote>Introduction</blockquote><p><strong>Spring Boot Profiles</strong> provide developers with a powerful way to manage environment-specific configurations. Whether you’re in development, testing, or production, profiles let you define tailored settings, ensuring your application runs smoothly across different environments. This feature simplifies deployment scenarios and enhances flexibility.</p><p>In this article, we’ll explore <strong>Spring Boot Profiles</strong> in depth, including how to define and use them effectively for better application management.</p><blockquote>What are profiles?</blockquote><p>Spring Boot Profiles allow developers to define multiple configuration sets for their application, depending on the target environment. For instance:</p><ul><li>Create beans conditionally based on the active profile.</li><li>Use a separate database for testing and development.</li></ul><p>You can define profiles in:</p><ul><li><strong>Property files</strong> (e.g., application-dev.properties)</li><li><strong>YAML files</strong> (e.g., application.yml)</li><li><strong>Java code</strong> (programmatically activating profiles)</li></ul><p>By default, Spring Boot activates the default profile if no other is s</p><blockquote>Using profiles in Spring Boot</blockquote><p>Now that you understand the benefits of using profiles in Spring Boot, let’s go over how to use them effectively.</p><h3>Defining profiles</h3><p>Profiles can be defined using property files or YAML files. For example, you might have an <strong>application-dev.properties</strong> file for your development environment and an <strong>application-prod.properties</strong> file for your production environment. To activate a profile, you can set the<strong> spring.profiles.active</strong> property in your application.properties file:</p><pre>spring.profiles.active=dev</pre><p>This will activate the <strong>dev</strong> profile, and Spring Boot will load the <strong>application-dev.properties</strong>.</p><p><strong>Note</strong>: When you define the “spring.profiles.active” property in your “application.properties” file, Spring Boot will still load that file as well as the properties file specific to the active profile. This means that any properties defined in the “application.properties” file will be overridden by properties defined in the active profile’s properties file if they have the same key.</p><blockquote>Example</blockquote><ul><li>Create different property files for each environment</li></ul><p>Create a application.properties file in your src/main/resources directory, containing the default database configuration:</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/myapp<br>spring.datasource.username=myappuser<br>spring.datasource.password=myapppass</pre><p>Add another properties file named application-dev.properties in the same directory, containing the configuration for the development database:</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/myapp_dev<br>spring.datasource.username=myappuser_dev<br>spring.datasource.password=myapppass_dev</pre><p>Create a third properties file named application-prod.properties in the same directory, containing the configuration for the production database:</p><pre>spring.datasource.url=jdbc:mysql://prod-db.example.com:3306/myapp<br>spring.datasource.username=myappuser_prod<br>spring.datasource.password=myapppass_prod</pre><ul><li>Configure your application to use profiles</li></ul><p>In your application.properties file, add the following line to indicate which profiles should be active:</p><pre>spring.profiles.active=dev</pre><p>By default, Spring Boot will use the appropriate information provided in the properties file related to the active profile for configuring the data source connection. The properties that Spring Boot uses to configure the data source connection include:(spring.datasource.url , spring.datasource.username , spring.datasource.password).</p><ul><li>Run your application with different profiles</li></ul><p>To run your application with the development profile and use theapplication-dev.properties file for configuration, set thespring.profiles.active property to dev, or when you are running your application use: — spring.profiles.active property.</p><pre>java -jar app.jar --spring.profiles.active=dev</pre><p>By using profiles in this way, you can easily switch between different database configurations for different environments, without having to modify your application code or configuration files.</p><h3>Best Practices for Spring Boot Profiles</h3><p>Follow these best practices to maximize the effectiveness of Spring Boot Profiles:</p><ul><li><strong>Use Meaningful Names:</strong> Profile names like local, dev, prod, or test should clearly describe their purpose.</li><li><strong>Define Defaults:</strong> Include default configurations in application.properties to ensure the app runs even if no profile is specified.</li><li><strong>Leverage Environment Variables:</strong> Use environment variables to set the active profile dynamically without changing the code.</li></ul><h3>Benefits of Using Spring Boot Profiles</h3><ul><li><strong>Seamless Environment Switching:</strong> Easily switch between development and production configurations without code changes.</li><li><strong>Centralized Configuration Management:</strong> Keep environment-specific settings organized in separate files.</li><li><strong>Improved Scalability:</strong> Easily add new environments, such as QA or staging, without disrupting your existing configurations.</li></ul><p>Thanks for Reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e00159f0542" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/getting-started-with-spring-boot-profiles-1e00159f0542">Spring Boot Profiles: Step-by-Step Guide for Developers</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens Internally  When You Start A Spring Boot Application(Part1)]]></title>
            <link>https://medium.com/javarevisited/what-happens-internally-when-you-start-a-spring-boot-application-part1-a683a64c1be8?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a683a64c1be8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 18:47:30 GMT</pubDate>
            <atom:updated>2024-05-29T20:28:51.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Happens Internally When You Start A Spring Boot Application(Part1)</h3><h4>ApplicationContext creation/registration , AutoConfiguration .. .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJXRxHNxWbaVv79V" /></figure><blockquote>Explore my latest article series on <a href="https://javalaunchpad.com/">JavaLaunchpad</a>, where you’ll find in-depth knowledge and practical examples covering a wide range of components and features in Spring MVC.</blockquote><blockquote><a href="https://javalaunchpad.com/introduction-to-spring-mvc-architecture/">1- Spring MVC Architecture</a></blockquote><blockquote><a href="https://javalaunchpad.com/dispatcherservlet-configuration/">2- The 3 Ways to Configure DispatcherServlet In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/most-popular-spring-mvc-annotations/">3- Most Popular Spring MVC Annotations</a></blockquote><blockquote><a href="https://javalaunchpad.com/data-binding/">4- Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/spring-mvc-handlerinterceptor/">5- How to Use HandlerInterceptor In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/customizing-data-binding-in-spring-mvc-creating-your-own-formatter/">6- Customizing Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/understanding-the-difference-between-handler-interceptors-and-filters-in-spring-mvc/">7- HandlerInterceptor VS. Filter</a></blockquote><blockquote>Introduction</blockquote><p>In this article, <strong>we will explore what happens when we click the ‘run’ button in our IDE to run our Spring Boot application.</strong> There are many interesting things to discover, so get ready to dive into the internal workings of Spring Boot.</p><p>As we all know, the main method of the project serves as the entry point, but what actually happens when this method is executed ?</p><p>This is the <a href="https://javarevisited.blogspot.com/2012/03/javalangnosuchmethoderror-main.html">main method</a> we’ll be discussing:</p><pre>@SpringBootApplication<br>public class SpringBootIntroApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(SpringBootIntroApplication.class, args);<br>    }<br><br>}</pre><p>Despite the simplicity of <a href="https://www.java67.com/2018/06/top-15-spring-boot-interview-questions-answers-java-jee-programmers.html">Spring Boot’s startup process</a>, there is a lot going on behind the scenes. In just one line of code, Spring Boot is able to perform a wide range of tasks. Let’s take a deeper dive to understand exactly what is happening under the hood</p><blockquote>run() method in the SpringApplication class .</blockquote><pre>public ConfigurableApplicationContext run(String... args) {<br>    long startTime = System.nanoTime();<br>    DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();<br>    ConfigurableApplicationContext context = null;<br>    this.configureHeadlessProperty();<br>    SpringApplicationRunListeners listeners = this.getRunListeners(args);<br>    listeners.starting(bootstrapContext, this.mainApplicationClass);<br><br>    try {<br>        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);<br>        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);<br>        this.configureIgnoreBeanInfo(environment);<br>        Banner printedBanner = this.printBanner(environment);<br>        context = this.createApplicationContext();<br>        context.setApplicationStartup(this.applicationStartup);<br>        this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);<br>        this.refreshContext(context);<br>        this.afterRefresh(context, applicationArguments);<br>        Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);<br>        if (this.logStartupInfo) {<br>            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup);<br>        }<br><br>        listeners.started(context, timeTakenToStartup);<br>        this.callRunners(context, applicationArguments);<br>    } catch (Throwable var12) {<br>        this.handleRunFailure(context, var12, listeners);<br>        throw new IllegalStateException(var12);<br>    }<br><br>    try {<br>        Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);<br>        listeners.ready(context, timeTakenToReady);<br>        return context;<br>    } catch (Throwable var11) {<br>        this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null);<br>        throw new IllegalStateException(var11);<br>    }<br>}</pre><p>Note: The following code snippet is an internal implementation of the run method in a<a href="https://www.java67.com/2022/12/10-projects-ideas-to-learn-spring-boot.html"> Spring Boot project</a>. We will use it as a reference in this article and is not expected to understand it 100 % .</p><p>When you invoke the run method of SpringApplication, it creates a WebApplicationContext for your web application. If you look at the implementation of the run method, you will see that its return type is ConfigurableApplicationContext. This interface is implemented directly or indirectly by all the <a href="https://javarevisited.blogspot.com/2012/11/difference-between-beanfactory-vs-applicationcontext-spring-framework.html">Application Contexts .</a></p><p>The type of WebApplicationContext that is created depends on the type of your web application. For example, if your application is a Servlet-based web application, Spring Boot creates a AnnotationConfigServletWebServerApplicationContext. On the other hand, if your application is a Reactive web application, Spring Boot creates a AnnotationConfigReactiveWebServerApplicationContext. This way, Spring Boot determines the type of your web application and creates the appropriate WebApplicationContext accordingly.</p><p>I understand that you’re curious about how <a href="https://medium.com/javarevisited/10-free-spring-boot-tutorials-and-courses-for-java-developers-53dfe084587e">Spring Boot</a> determines the type of web application. It’s a great question, and I’d be happy to explain it to you.</p><p>Let me explain this to you, Spring Boot internally classifies web applications into two categories: <a href="https://medium.com/javarevisited/7-best-webflux-and-reactive-spring-boot-courses-for-java-programmers-33b7c6fa8995">Reactive </a>and <a href="http://javarevisited.blogspot.sg/2017/09/dispatcherservlet-of-spring-mvc-10-points-to-remember.html">Servlet applications</a> using the WebApplicationType enumeration.</p><p>in the constructor of the SpringApplication class you will find this line :</p><pre>this.webApplicationType = WebApplicationType.deduceFromClasspath();</pre><p>spring-boot uses the deduceFromClasspath() method to determine the type of web application based on the presence of certain dependencies on the classpath. If it finds the spring-boot-starter-web dependency, it will assume that the application is a Servlet-based web application and set the webApplicationType attribute to SERVLET. Similarly, if it finds the spring-boot-starter-reactive dependency, it will assume that the application is a reactive web application and set the webApplicationType to REACTIVE. If none of these dependencies are found, they webApplicationType will be set to NONE.</p><p>based on this application type Spring Boot will create the appropriate application context but how?</p><pre>context = this.createApplicationContext();</pre><pre>protected ConfigurableApplicationContext createApplicationContext() {<br> return this.applicationContextFactory.create(this.webApplicationType); <br>}</pre><p>The createApplicationContext() method in SpringApplication creates the appropriate application context based on the detected webApplicationType. It delegates the task of creating the context to an instance of ApplicationContextFactory, which is passed the detected webApplicationType as a parameter.</p><p>The ApplicationContextFactory interface defines a single method create(WebApplicationType), which returns a new ConfigurableApplicationContext based on the given WebApplicationType.</p><p>to check if the run method return the appropriate webApplicationContext :</p><pre>public static void main(String[] args) {<br>    ConfigurableApplicationContext run = SpringApplication.run(SpringBootIntroApplication.class, args);<br>    System.out.println(run instanceof AnnotationConfigServletWebServerApplicationContext );<br><br>}</pre><blockquote>what’s happened after the context get created ?</blockquote><p>The this.refreshContext(context) method in the run() method of SpringApplication triggers a refresh of the application context. This means that the application context will be initialized and configured with all the necessary beans and components required to run the application.</p><p>During the refresh process, Spring will scan the application’s classpath for all components that have been annotated with <a href="https://www.java67.com/2022/06/difference-between-component-service-repository-in-spring.html">@Component</a> or other annotations, and will create and configure instances of those components as necessary. It will also load and configure any other beans that are defined in the application context, such as those defined in XML configuration files or through Java configuration classes.</p><p>Once the application context has been fully refreshed and initialized, the application can start handling requests or performing other tasks.</p><figure><a href="https://www.java67.com/2021/02/spring-boot-actuator-interview-questions-answers-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8cMYwk5OByXUL2o5S4Dow.png" /></a></figure><p>it’s important to note that the run the method does much more than that, we focus only on how the run() method creates the WebApplicationType.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a683a64c1be8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/what-happens-internally-when-you-start-a-spring-boot-application-part1-a683a64c1be8">What Happens Internally  When You Start A Spring Boot Application(Part1)</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discovering the Magic of Spring Boot: A Before & After Story !]]></title>
            <link>https://medium.com/javarevisited/discovering-the-magic-of-spring-boot-a-before-after-story-293ee5b3be7f?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/293ee5b3be7f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 14:51:28 GMT</pubDate>
            <atom:updated>2023-07-19T00:09:46.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot vs Spring : Discovering the Magic of Spring Boot.</h3><h4>Explore Spring Boot Starters , AutoConfiguration , …</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*45ydLIzIqBkNtMR6" /></figure><p>In this article, we will explore what <a href="https://medium.com/javarevisited/top-10-courses-to-learn-spring-boot-in-2020-best-of-lot-6ffce88a1b6e">Spring Boot</a> provides for Java developers by comparing the process of creating a web application with and without <a href="https://javarevisited.blogspot.com/2018/02/top-5-spring-microservices-courses-with-spring-boot-and-spring-cloud.html">Spring Boot</a>.</p><blockquote>The first version of Spring Boot (version 1.0.0) was released on April 1, 2014.</blockquote><h3>The Legacy Way of Creating Java Web Applications With Spring .</h3><p>Our task for today is to create a simple “Hello, World” web application using <a href="https://medium.com/javarevisited/my-favorite-spring-mvc-courses-for-java-developers-5ede7f85dd88">Spring MVC</a> only. In this part, we will explore what needs to be configured in order to get our application up and running. First, let’s begin with a quick introduction to <a href="https://javarevisited.blogspot.com/2018/11/top-20-spring-mvc-interview-questions-answers-for-java-developers.html">Spring MVC</a>.</p><p>Spring MVC is the module responsible for developing server-rendered web applications. However, before diving into the development of our business logic, we need to configure several things to ensure that our application runs correctly.</p><p><strong>1. Install a web container such as Tomcat</strong> : A web container provides a complete environment for running web applications. For example, a web container like Tomcat can handle HTTP requests by passing the request to the <a href="https://www.java67.com/2017/06/what-is-use-of-dispatcherservlet-in-spring-mvc.html">DispatcherServlet </a>and sending back the response to the client. It is also responsible for managing the lifecycle of the DispatcherServlet, including its creation, destruction, initialization, and more.</p><p><strong>2.</strong> <strong>DispatcherServlet configuration</strong> : The DispatcherServlet is responsible for handling HTTP requests that come from clients, but in order to function, it requires various components or beans such as the <a href="https://javarevisited.blogspot.com/2017/08/what-does-internalresourceviewresolver-do-in-spring-mvc.html">ViewResolver</a>, HandlerMapping, and <a href="https://www.java67.com/2022/06/difference-between-component-service-repository-in-spring.html">Controllers</a>. In Spring, the responsibility of creating and managing these application beans is assigned to the Spring IoC container, with the WebApplicationContext being the implementation used in a web environment. As a result, the DispatcherServlet also requires an object from the WebApplicationContext to obtain all the necessary beans.</p><p><strong>3. dependency Management</strong> : Dependency management can be a challenging aspect of developing web applications. Often, to use a specific module in Spring, multiple dependencies must be included, which may need to be compatible in terms of version. This can make managing dependencies a complex and time-consuming process, requiring careful attention to detail to ensure that all dependencies are correctly specified and compatible with each other.</p><p>I have already explained how to create a simple web application from scratch with all the necessary configurations in one of my previous articles. You can check it out here.</p><p><a href="https://medium.com/javarevisited/spring-mvc-part-1-build-your-first-hello-world-web-application-2c6e1ad54e5e">Spring MVC Part 1: The Big Picture</a></p><p>Before moving on to the second part of this article, be sure to explore the configuration of the Spring MVC environment and experience the complexity behind this configuration.</p><h3>Spring MVC Applications Using Spring Boot .</h3><blockquote>Create a Spring Boot Project</blockquote><p>There are several ways to create a Spring Boot project:</p><ul><li>Spring Initializr: Spring Initializr is a web-based tool that generates a Spring Boot project with the required dependencies and configurations. You can select the dependencies you need and download a ZIP file containing the project.</li><li>Spring Boot CLI: Spring Boot CLI is a command-line tool that can be used to quickly create Spring Boot projects. You can use the “spring init” command to create a new project with the desired dependencies.</li><li>IDE : if you are using an IDE like Eclipse or IntelliJ IDEA You can use the Spring Initializr integration in the IDE.</li></ul><p>In this article, I will be utilizing the Spring Initializr, integrated with my IDE (IntelliJ IDEA), to generate our project.</p><figure><a href="https://www.java67.com/2022/12/10-projects-ideas-to-learn-spring-boot.html"><img alt="" src="https://cdn-images-1.medium.com/max/802/1*qETEDhr9QGHBDICQlRBXFA.png" /></a></figure><p>After selecting the build tool, Java version, project name, and packaging, proceed to the next step and select the required dependencies for your project. Since we are building a simple web application, choose the Spring web dependency.</p><figure><a href="https://javarevisited.blogspot.com/2022/01/spring-boot-reactjs-example-for-java.html"><img alt="" src="https://cdn-images-1.medium.com/max/800/1*izl_fragYHJOOEm5D-2OxA.png" /></a></figure><p>Finally, click the “Create” button and congratulations, your project has been successfully created!</p><blockquote>how Starters simplify dependency management ?</blockquote><p>Starters are a feature in the Spring Framework that simplify dependency management by providing a set of pre-configured dependencies for a specific purpose. A Starter is essentially a collection of dependencies that are commonly used together in a certain type of application, such as a web application .</p><p>Here are some ways in which Starters simplify dependency management:</p><ol><li>Pre-configured dependencies: Starters provide a set of pre-configured dependencies that work well together for a specific purpose. This saves developers time and effort in manually identifying and adding the necessary dependencies to their project.</li><li>Version management: Starters ensure that all dependencies included in the Starter are compatible with each other, avoiding version conflicts and other issues that can arise when managing dependencies manually.</li></ol><p>For example, if you want to build a web application with Spring MVC, you can use the “spring-boot-starter-web” starter, which includes all the necessary dependencies for building a web application, such as Spring MVC, embedded Tomcat server, Jackson (for JSON serialization), and various other libraries.</p><p>By including a starter in your project, Spring Boot will automatically pull in all the necessary dependencies and configure them for you based on sensible defaults.</p><blockquote>AutoConfiguration In Spring Boot what this mean ?</blockquote><p>Autoconfiguration is a powerful feature of Spring Boot that allows it to automatically configure the various components of your application based on the dependencies that are included in your classpath.</p><p>For example, if you include the “spring-boot-starter-web” starter in your project, Spring Boot will automatically configure a web application for you. This includes configuring the embedded Tomcat server, configuring DispatcherServlet &amp; more .</p><p>Autoconfiguration in Spring Boot helps to simplify and streamline the process of setting up and configuring your application. It can save you time and effort in configuring each individual component and ensures that your application follows best practices and is properly configured.</p><p>Ex : In the project that we just created we choose the Spring web starter so let’s explore what spring boot will autoconfigure for as !</p><figure><a href="https://www.java67.com/2018/06/top-15-spring-boot-interview-questions-answers-java-jee-programmers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TgJ96zEt5c1cUS3fdvLTw.png" /></a></figure><p>Spring Boot Actually automatically configure several things for as , including:</p><ol><li>DispatcherServlet &amp; WebApplicationContext .</li><li>Embedded web server: Spring Boot includes an embedded web server (Tomcat, Jetty or Undertow) that is configured for you by default. This means that you don’t need to manually install and configure an external web server, as Spring Boot will automatically start and configure the embedded server.</li></ol><blockquote>What is a FAT jar ?</blockquote><p>Spring Boot gives us a “FAT jar” because it packages all of the application’s dependencies, including the application server, into a single, executable JAR file. This means that the JAR file contains everything needed to run the application, and it can be run in every machine with only a JRE installed (we don’t need to configure an additional web container to deploy our jar ).</p><p>we hope this article has provided you with a better understanding of the Spring Boot benefits and how it simplifies the process of building and deploying Spring applications.</p><p>However, there is much more to learn about Spring Boot’s autoconfiguration and how it works behind the scenes. In our next article, we will take a deeper dive into the inner workings of Spring Boot’s autoconfiguration, exploring how it identifies and configures beans, how it resolves dependencies, and much more.</p><p>So, stay tuned for our next article, where we will explain in depth how Spring Boot’s autoconfiguration works behind the scenes.</p><p>thanks for reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293ee5b3be7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/discovering-the-magic-of-spring-boot-a-before-after-story-293ee5b3be7f">Discovering the Magic of Spring Boot: A Before &amp; After Story !</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strings in Java : A Comprehensive Guide for Beginners]]></title>
            <link>https://medium.com/javarevisited/strings-in-java-a-comprehensive-guide-for-beginners-b66085dd8332?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/b66085dd8332</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 18:34:15 GMT</pubDate>
            <atom:updated>2023-02-12T15:53:33.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying the Java String Class: Everything You Need to Know</h3><h4>Immutability , String Pool , StringBuilder , StringBuffer &amp; more .</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sKoYmATJ-Cdf83hM" /></figure><p>In the world of programming, text manipulation is an essential part of many applications. As a Java developer, the <a href="https://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html">String class</a> is an invaluable tool that enables you to work with text data efficiently and effectively .</p><h4>The String Class in Java</h4><p>In Java, the String class is a class that represents character sequences. The <a href="https://www.java67.com/2014/01/why-string-class-has-made-immutable-or-final-java.html">String class is immutable</a>, which means that once a String object is created, its value cannot be changed. This is a fundamental aspect of the String class .</p><h4>Important String Methods</h4><p>The String class has several methods that allow us to manipulate and access the characters within a String object. Some of the most commonly used methods include:</p><blockquote><a href="https://javarevisited.blogspot.com/2020/04/5-ways-to-find-length-of-string-in-java.html">length()</a></blockquote><p>length() method used to return the number of characters in the String object.</p><p>Example:</p><pre>String name = &quot;John&quot;;<br>int length = name.length();<br>System.out.println(length); //4</pre><blockquote><a href="https://www.java67.com/2018/05/java-string-chartat-example-how-to-get-first-last-character.html">charAt()</a></blockquote><p>charAt() method used to return the character at the specified position within a string .</p><pre>char charAt(int  index)</pre><p>Example:</p><pre>String name = &quot;John Doe&quot;;<br>char character = name.charAt(0);<br>System.out.println( character); //J</pre><blockquote><a href="http://www.java67.com/2012/10/string-contains-and-indexof-example.html">indexOf()</a></blockquote><p>returns the index for a given character (return -1 if it can’t find the char or the string ).</p><p>In the java String class there are several variations of the indexOf method , that we can use to find the index of a character or a substring within a string . Here are the most commonly used variations of the indexOf :</p><pre>int indexOf(char ch)<br>int indexOf(char ch, index fromIndex)<br>int indexOf(String str)<br>int indexOf(String str, index fromIndex)</pre><p><strong>Note</strong>: Please keep in mind that, unlike charAt, indexOf will not throw an exception, it will return -1 instead</p><p><strong>Note</strong> : The fromIndex parameter is used to specify the starting point for Java&#39;s search .</p><p>Example :</p><pre>String string = &quot;hamza&quot;;<br>System.out.println(string.indexOf(&#39;h&#39;));   // 0<br>System.out.println(string.indexOf(&quot;za&quot;));    // 3<br>System.out.println(string.indexOf(&#39;a&#39;, 3));  // 4<br>System.out.println(string.indexOf(&quot;ha&quot;, 5));// -1<br></pre><blockquote><a href="https://javarevisited.blogspot.com/2013/08/difference-between-substr-vs-substring-in-JavaScript-tutorial-example.html">substring()</a></blockquote><p>returns a new String object that is a part of the original String object.</p><p>The method signature :</p><pre>int substring(int beginIndex)<br>int substring(int beginIndex, int endIndex)</pre><p>Example :</p><pre>String sentence  = &quot;java programming&quot;;<br>String java = sentence.substring(0, 4); //java<br></pre><p><strong>Note</strong>: Please keep in mind that the end index is exclusive (for example, sentence.substring(0, 4) returns a string that goes up to but does not include the character at index 4).</p><blockquote><a href="https://www.java67.com/2012/12/how-to-convert-string-from-lowercase-to-uppercase.html">toLowerCase() &amp; toUpperCase()</a></blockquote><p>returns a new String object that contains the original String object’s characters in lower case / upper case .</p><p>The method signatures are as follows :</p><pre>String toLowerCase( )<br>String toUpperCase( )</pre><p>Example :</p><pre>String name = &quot;HAMZA nassour &quot;;<br>String lowerCase = name.toLowerCase();<br>String upperCase = name.toUpperCase();<br>System.out.println(&quot;The lower case string is: &quot; + lowerCase); // hamza nassour<br>System.out.println(&quot;The upper  case string is: &quot; + upperCase); // HAMZA NASSOUR</pre><blockquote><a href="http://javarevisited.blogspot.sg/2015/01/why-override-equals-hashcode-or-tostring-java.html">equals() &amp; equalsIgnoreCase()</a></blockquote><p>equals() compares the contents of two String objects and returns a boolean indicating whether they are equal or not.</p><p>Example:</p><pre>String name1 = &quot;John Doe&quot;;<br>String name2 = &quot;John Doe&quot;;<br>boolean isEqual = name1.equals(name2);<br>System.out.println(&quot;The strings are equal: &quot; + isEqual);</pre><p><strong>Note</strong> : the equalsIgnoreCase() method is the same as equals() method with one exception is that method don’t care about the cases ( hamza == HAMZA for the equalsIgnoreCase() ).</p><pre>System.out.println(&quot;hamza&quot;.equalsIgnoreCase(&quot;HAMZA&quot;));  //true</pre><blockquote>startsWith() &amp; endsWith() .</blockquote><p>startsWith()/endsWith() Is a method that checks whether a string starts/end with a given substring or not , return a boolean value .</p><p>For example,</p><pre>&quot;hamza&quot;.startsWith(&quot;ha&quot;)  //true<br>&quot;hello&quot;.startsWith(&quot;hi&quot;)  // false.<br>&quot;hamza&quot;.endsWith(&quot;a&quot;)  //true<br>&quot;hello&quot;.endsWith(&quot;za&quot;)  // false.</pre><p><strong>Note</strong> : There are some other interesting methods that we have not covered, but you can explore them in the official documentation. <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html">here</a></p><h4>The String Pool Constant</h4><p>In Java, the <a href="http://javarevisited.blogspot.sg/2016/07/difference-in-string-pool-between-java6-java7.html">String pool</a> is a special area of memory where all of the constant String objects are stored. The JVM automatically places all constant String literals in the String pool. This means that if two String objects have the same contents, they will refer to the same object in the String pool.</p><p>Example:</p><pre>String name1 = &quot;John Doe&quot;;<br>String name2 = &quot;John Doe&quot;;<br>System.out.println(name1 == name2); // True</pre><p>The main purpose of the String Pool is to optimize memory usage by ensuring that there is only one instance of each unique string literal in the system.</p><p>Note : when we Use the String Constructor to construct our Strings they will not belongs to the String pool (String str = new String(“hamza”) str is considered as an object and it will be created in the heap area ).</p><h4>StringBuilder &amp; StringBuffer</h4><p><a href="https://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html">StringBuilder </a>(introduced in java 5) is a class in Java that allows for efficient manipulation of strings. Unlike regular strings, which are immutable, StringBuilder can be modified without creating a new object each time.</p><p>For example, let’s say you have a loop that is concatenating a large number of characters together:</p><pre>String result = &quot;&quot;;<br>for (char  c = &#39;a&#39; ; c&lt;= &#39;z&#39; ; c++) {<br>    result = result+ c ;<br>}</pre><p>let’s count the number of string objects created in this example :</p><p>In each step of the loop a new object get created ( representing the concatenation ) so the total will be 26 different object and don’t forget the first the empty string in the first line -&gt; 27 object in total which can be very inefficient .</p><p>Using StringBuilder can make this code much faster and more memory-efficient :</p><pre>StringBuilder  result = new StringBuilder();<br>for (char  c = &#39;a&#39; ; c&lt;= &#39;z&#39; ; c++) {<br>    result.append(c);<br>}</pre><p>This code only creates one StringBuilder object, and the append() method efficiently adds each char to the end of the string. This can be much faster and more memory-efficient than using the string concatenation operator (+) in a loop.</p><p>the StringBuilder class in Java is used for creating and manipulating mutable strings. It has many methods for manipulating the content of the string, including append(), insert(), reverse(), delete(), and deleteCharAt() . It also has some of the same methods as the String class, such as charAt() , indexOf(), length(), and substring(), in addition to the method toString() for converting the StringBuilder to a String .</p><p><strong>difference between StringBuilder and StringBuffer</strong></p><p>The Both class has the same fonctionalities with one difference is that StringBuilder is not thread-safe while StringBuffer is thread-safe .</p><p>In other words, if multiple threads are accessing a StringBuilder object simultaneously, there may be synchronization issues, leading to unexpected behavior. On the other hand, if multiple threads are accessing a StringBuffer object simultaneously, the access is synchronized.</p><p>Because StringBuffer ensures thread safety through synchronization, it may be slower than StringBuilder, which does not have the overhead of synchronization. Therefore, StringBuilder is generally preferred for single-threaded scenarios, while StringBuffer is more suitable for multi-threaded scenarios.</p><p>I hope you guys understood Java Strings &amp; Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b66085dd8332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/strings-in-java-a-comprehensive-guide-for-beginners-b66085dd8332">Strings in Java : A Comprehensive Guide for Beginners</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optional Class in Java 8: Making Your Code More Clear and Concise .]]></title>
            <link>https://medium.com/javarevisited/optional-class-in-java-8-making-your-code-more-clear-and-concise-62af0712910d?source=rss-4aed7f746d32------2</link>
            <guid isPermaLink="false">https://medium.com/p/62af0712910d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[Hamza Nassour]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 00:24:58 GMT</pubDate>
            <atom:updated>2024-05-29T20:29:35.255Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optional Class in Java 8: Making Your Code More Clear and Concise .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wyJQ49QbSaGkv9cg" /></figure><blockquote>Explore my latest article series on <a href="https://javalaunchpad.com/">JavaLaunchpad</a>, where you’ll find in-depth knowledge and practical examples covering a wide range of components and features in Spring MVC.</blockquote><blockquote><a href="https://javalaunchpad.com/introduction-to-spring-mvc-architecture/">1- Spring MVC Architecture</a></blockquote><blockquote><a href="https://javalaunchpad.com/dispatcherservlet-configuration/">2- The 3 Ways to Configure DispatcherServlet In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/most-popular-spring-mvc-annotations/">3- Most Popular Spring MVC Annotations</a></blockquote><blockquote><a href="https://javalaunchpad.com/data-binding/">4- Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/spring-mvc-handlerinterceptor/">5- How to Use HandlerInterceptor In Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/customizing-data-binding-in-spring-mvc-creating-your-own-formatter/">6- Customizing Data Binding in Spring MVC</a></blockquote><blockquote><a href="https://javalaunchpad.com/understanding-the-difference-between-handler-interceptors-and-filters-in-spring-mvc/">7- HandlerInterceptor VS. Filter</a></blockquote><h3>Why Optional Class ?</h3><p>The Optional class in Java 8 is a container object which is used to contain a value that might or might not be present. It was introduced as a way to help reduce the number of <a href="https://www.java67.com/2021/05/how-to-solve-nullpointerexception-in-java.html">NullPointerExceptions </a>that occur in Java code. It is a part of the java.util package and was added to Java as part of Java 8.</p><p><a href="https://javarevisited.blogspot.com/2017/04/10-examples-of-optional-in-java-8.html">Optional </a>is a container that either contains a non-null value or nothing(empty Optional ). The Optional class is an implementation of the Null Object pattern, which is a design pattern that was designed to reduce the number of null checks in code. With Optional, you can write cleaner and more concise code that is easier to maintain.</p><p>One of the key benefits of using <a href="https://www.java67.com/2018/06/java-8-optional-example-ispresent-orElse-get.html">Optional </a>is that it forces you to handle the case where the value is absent. This means that you are less likely to miss important checks in your code and reduces the risk of NullPointerException. If a value is not present, you can either provide a default value or throw an exception.</p><p>Example (Problem with null):</p><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        Student Student = getStudentWithName(&quot;hamza&quot;);<br>        System.out.println(Student.getName());<br><br>    }<br><br>    public  static Student  getStudentWithName(String name ){<br>        // lets suppose that our database contain only 2 students ahmed and hamza .<br>        if (name.equals(&quot;hamza&quot;) || name.equals(&quot;ahmed&quot;)) {<br>            return new Student(name , 22 , &quot;Morocco&quot;);<br>        } else {<br>            return null ;<br>        }<br>    }<br><br>}</pre><p>It’s obvious that getStudentWithName() can return a null if there is no student with the given name =&gt; NullPointerException will occur when we call the getName() method (student = null ).</p><p>To handle this case, we should implement some form of conditional logic based on the result returned by the method.</p><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        Student Student = getStudentWithName(&quot;hamza&quot;);<br>        if(student != null){<br>             System.out.println(Student.getName());<br>        }else {<br>          System.out.println(&quot;no Student with the given name &quot;);<br>        }<br><br>    }<br><br>   public  static Student  getStudentWithName(String name ){<br>        // lets suppose that our database contain only 2 students ahmed and hamza .<br>        if (name.equals(&quot;hamza&quot;) || name.equals(&quot;ahmed&quot;)) {<br>            return new Student(name , 22 , &quot;Morocco&quot;);<br>        } else {<br>            return null ;<br>        }<br>    }<br><br>}</pre><p>To avoid NullPointerException problems, let’s examine what the Optional API offers.</p><h3>Optional class methods</h3><h4>Optional.ofNullable(T) , Optional.of(T) , Optional.empty() .</h4><ul><li>Optional.ofNullable()</li></ul><p>To use the Optional class, simply wrap your object in an Optional object like this: Optional&lt;T&gt; optional = Optional.ofNullable(T). You can then use the various methods provided by Optional to handle the cases where the value is present or not. For example, the isPresent() method returns true if the value is present, and false if it is not.</p><ul><li>Optional.of()</li></ul><p>This method behave like the ofNullable() function it will return an Optional for the given value the only difference is that the of() method does not allow to construct an Optional object around a null value .</p><pre>Optional&lt;Student&gt; student = Optional.of(null);</pre><p>this line will throw a NullPointerException .</p><ul><li>empty()</li></ul><p>this method will simply generate an empty Optional (no value ).</p><pre>Optional&lt;T&gt; empty = Optional.empty();</pre><p>The Optional class provides several methods that can be used to interact with the value that is stored inside the Optional. For example, the isPresent() method can be used to check if a value is present or not. If a value is present, you can use the get() method to retrieve it.</p><p>now let’s try to refactor our exemple using Optional API .</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Optional&lt;Student&gt; student = Optional.ofNullable(getStudentWithName(&quot;hamza&quot;));<br>        if (student.isPresent()) {<br>            System.out.println(student.get().getName());<br>        } else {<br>            System.out.println(&quot;Student  is not present&quot;);<br>        }<br>    }<br><br>   public  static Student  getStudentWithName(String name ){<br>        // lets suppose that our database contain only 2 students ahmed and hamza .<br>        if (name.equals(&quot;hamza&quot;) || name.equals(&quot;ahmed&quot;)) {<br>            return new Student(name , 22 , &quot;Morocco&quot;);<br>        } else {<br>            return null ;<br>        }<br>    }<br><br>}</pre><p>Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use.Of course, there are still if-else blocks in this logic, but let’s examine other useful methods provided by the Optional API to reduce its use.</p><h4>Make your code more concise using orElse() , orElseThrow() .</h4><ul><li>orElse()</li></ul><p>orElse is a method in the Java Optional class that is used to return the value wrapped in the Optional, if it is present, or a default value if it is not. It takes a default value as an argument and returns it if the Optional is empty.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Student  student = Optional.ofNullable(getStudentWithName(&quot;hamza&quot;)).orElse(new Student(&quot;no one&quot;, 0, &quot;Unknown&quot;));<br>            System.out.println(student.getName());<br>    }<br><br>    public  static Student  getStudentWithName(String name ){<br>        // lets suppose that our database contain only 2 students ahmed and hamza .<br>        if (name.equals(&quot;hamza&quot;) || name.equals(&quot;ahmed&quot;)) {<br>            return new Student(name , 22 , &quot;Morocco&quot;);<br>        } else {<br>            return null ;<br>        }<br>    }<br><br>}</pre><ul><li>orElseThrow() .</li></ul><p>orElseThrow is a method in the Java Optional class that is used to throw an exception if the Optional is empty. Unlike orElse, which returns a default value, orElseThrow allows you to throw a custom exception.</p><p>Here’s an example:</p><pre>public class Main {<br>    public static void main(String[] args) throws StudentNotFoundException {<br>        Student  student = Optional.ofNullable(getStudentWithName(&quot;fs&quot;)).orElseThrow(()-&gt; new StudentNotFoundException(&quot;the Student is not Present &quot;));<br>            System.out.println(student.getName());<br>    }<br><br>    public  static Student  getStudentWithName(String name ){<br>        // lets suppose that our database contain only 2 students ahmed and hamza .<br>        if (name.equals(&quot;hamza&quot;) || name.equals(&quot;ahmed&quot;)) {<br>            return new Student(name , 22 , &quot;Morocco&quot;);<br>        } else {<br>            return null ;<br>        }<br>    }<br><br>}</pre><p>In conclusion, the Optional class in Java 8 is a useful tool for reducing the number of NullPointerExceptions in your code. It provides a clean and concise way to handle values that might or might not be present and reduces the risk of missing important checks in your code.</p><h4><a href="https://medium.com/@hamza.nassour13/subscribe">SUBSCRIPTION</a></h4><p>If you enjoy what I am writing, consider subscribing to my email list to receive notifications whenever I post something new.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62af0712910d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/optional-class-in-java-8-making-your-code-more-clear-and-concise-62af0712910d">Optional Class in Java 8: Making Your Code More Clear and Concise .</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>