<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: William</title>
    <description>The latest articles on Forem by William (@wkreuch).</description>
    <link>https://forem.com/wkreuch</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1235356%2F0601ca3e-e556-4403-9b7f-a0ced5a039f1.jpg</url>
      <title>Forem: William</title>
      <link>https://forem.com/wkreuch</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/wkreuch"/>
    <language>en</language>
    <item>
      <title>When to Use LinkedList vs. ArrayList in Java: A Practical Guide with a Spring Boot Example</title>
      <dc:creator>William</dc:creator>
      <pubDate>Tue, 19 Aug 2025 19:01:56 +0000</pubDate>
      <link>https://forem.com/wkreuch/when-to-use-linkedlist-vs-arraylist-in-java-a-practical-guide-with-a-spring-boot-example-2b4b</link>
      <guid>https://forem.com/wkreuch/when-to-use-linkedlist-vs-arraylist-in-java-a-practical-guide-with-a-spring-boot-example-2b4b</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In the Java ecosystem, collections are fundamental for managing data efficiently. Two of the most common implementations of the List interface are ArrayList and LinkedList. Both allow storing ordered elements with support for duplicates and index-based access, but they differ significantly in their internal structure and performance. Choosing the right implementation can drastically impact an application’s performance, especially in scenarios involving high data volumes or frequent operations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Differences
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;ArrayList:&lt;/strong&gt; Based on a dynamic array. Elements are stored in contiguous memory locations. When the array reaches its capacity, a new, larger array is created, and elements are copied (resize).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LinkedList:&lt;/strong&gt; Based on a doubly linked list. Each element is a node containing the value and references to the previous and next nodes. No contiguous allocation, allowing flexible expansion without massive copying.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Advantages and Disadvantages
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;ArrayList&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Advantages: Excellent for sequential iteration (via enhanced for-loop or iterator) and random access. More CPU cache-friendly due to memory locality.&lt;/li&gt;
&lt;li&gt;Disadvantages: Insertions and removals at the start or middle require shifting elements, which can be costly for large lists.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;LinkedList&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Advantages: Constant-time operations at the start or end. Implements Queue and Deque, making it versatile for queues or stacks.&lt;/li&gt;
&lt;li&gt;Disadvantages: Slow random access due to list traversal. Higher memory usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  When to Use ArrayList
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Frequent random access: If you need to access elements by index often (e.g., paginating results in an API).&lt;/li&gt;
&lt;li&gt;Read-heavy lists: Applications where the list is populated once and read/iterated multiple times, like configuration lists or query results.&lt;/li&gt;
&lt;li&gt;Fixed or predictable size: When the number of elements is stable, avoiding frequent resizes.&lt;/li&gt;
&lt;li&gt;Real-world examples: Product lists in an e-commerce system (access by ID), search query results, or static data caches.
Avoid ArrayList if there are many insertions/removals in the middle, as the O(n) cost can degrade performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  When to Use LinkedList
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Frequent insertions/removals at ends: Ideal for FIFO (Queue) or LIFO (Stack) scenarios, like task queues.&lt;/li&gt;
&lt;li&gt;Dynamic lists with constant changes: When order matters, but access is sequential or at the ends.&lt;/li&gt;
&lt;li&gt;Versatility as Queue/Deque: Useful for message queues, navigation histories, or asynchronous task processing.&lt;/li&gt;
&lt;li&gt;Real-world examples: Job queues in scheduling systems, media playlists (add/remove songs at ends), or stream processing buffers.
Avoid LinkedList for large lists with random access, as the O(n) traversal can be inefficient.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Real-World Example
&lt;/h2&gt;

&lt;p&gt;Let’s apply these concepts in a practical example: a simple REST API in Spring Boot for an e-commerce system. We’ll use:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;ArrayList&lt;/strong&gt; for storing available products (frequent random access, e.g., lookup by ID).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LinkedList&lt;/strong&gt; for a queue of pending orders (FIFO: process in order of arrival, with insertions at the end and removals at the start).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Model Classes&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Order {
    private Long id;
    private String description;

    public Order(Long id, String description) {
        this.id = id;
        this.description = description;
    }

    // Getters and Setters
}

public class Product {
    private Long id;
    private String name;

    public Product(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Service Class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class EcommerceService {

    private final List&amp;lt;Product&amp;gt; products = new ArrayList&amp;lt;&amp;gt;();
    private final List&amp;lt;Order&amp;gt; orderQueue = new LinkedList&amp;lt;&amp;gt;();

    public EcommerceService() {
        products.add(new Product(1L, "Product A"));
        products.add(new Product(2L, "Product B"));
        products.add(new Product(3L, "Product C"));
    }

    public Product getProductById(Long id) {
        int index = id.intValue() - 1; // Simulating mapping
        if (index &amp;gt;= 0 &amp;amp;&amp;amp; index &amp;lt; products.size()) {
            return products.get(index); // Fast access O(1)
        }
        return null;
    }

    public void addOrder(Order order) {
        orderQueue.addLast(order);
    }

    public Order processNextOrder() {
        if (!orderQueue.isEmpty()) {
            return orderQueue.removeFirst();
        }
        return null;
    }

    public List&amp;lt;Order&amp;gt; getOrderQueue() {
        return new LinkedList&amp;lt;&amp;gt;(orderQueue);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Controller Class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ecommerce")
public class EcommerceController {

    @Autowired
    private EcommerceService service;

    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable Long id) {
        return service.getProductById(id);
    }

    @PostMapping("/order")
    public String addOrder(@RequestBody Order order) {
        service.addOrder(order);
        return "Order added to queue!";
    }

    @GetMapping("/process")
    public Order processOrder() {
        return service.processNextOrder();
    }

    @GetMapping("/queue")
    public List&amp;lt;Order&amp;gt; viewQueue() {
        return service.getOrderQueue();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;ArrayList for Products:&lt;/strong&gt; Used for static or semi-static items. The &lt;em&gt;&lt;strong&gt;/product/{id}&lt;/strong&gt;&lt;/em&gt; endpoint accesses directly by index (simulated), leveraging O(1) for fast lookups. In a real e-commerce system, this is efficient for large catalogs where users search products by ID or paginate results.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LinkedList for Orders:&lt;/strong&gt; Acts as a FIFO Queue. Orders are added at the end (addLast) via POST &lt;em&gt;&lt;strong&gt;/order&lt;/strong&gt;&lt;/em&gt; and processed from the start (removeFirst) via GET /process. This ensures order-of-arrival processing, ideal to prevent new orders from jumping ahead. In real systems, this could integrate with a message broker like Kafka, but here it’s a simple in-memory queue.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Run the application&lt;/li&gt;
&lt;li&gt;Add orders via POST: Use Postman to send JSON { "id": 1, "description": "Urgent Order" } to &lt;a href="http://localhost:8080/ecommerce/order" rel="noopener noreferrer"&gt;http://localhost:8080/ecommerce/order&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Process: GET &lt;a href="http://localhost:8080/ecommerce/process" rel="noopener noreferrer"&gt;http://localhost:8080/ecommerce/process&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;View queue: GET &lt;a href="http://localhost:8080/ecommerce/queue" rel="noopener noreferrer"&gt;http://localhost:8080/ecommerce/queue&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Fetch product: GET &lt;a href="http://localhost:8080/ecommerce/product/1" rel="noopener noreferrer"&gt;http://localhost:8080/ecommerce/product/1&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>Three Ways to Perform Queries in Spring Boot</title>
      <dc:creator>William</dc:creator>
      <pubDate>Tue, 19 Aug 2025 17:11:28 +0000</pubDate>
      <link>https://forem.com/wkreuch/three-ways-to-perform-queries-in-spring-boot-4iij</link>
      <guid>https://forem.com/wkreuch/three-ways-to-perform-queries-in-spring-boot-4iij</guid>
      <description>&lt;p&gt;&lt;strong&gt;Spring Data JPA&lt;/strong&gt; provides three powerful methods to perform SELECT queries: &lt;em&gt;standard repository methods&lt;/em&gt;, &lt;em&gt;@Query annotations&lt;/em&gt;, and custom queries with &lt;em&gt;EntityManager&lt;/em&gt;. Each approach offers unique advantages and built-in protections against SQL Injection. Below, I’ll demonstrate these using a Product entity, ensuring secure and efficient queries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Standard Repository Methods
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Spring Data JPA&lt;/strong&gt; repositories provide built-in methods and allow custom queries through method naming conventions, with automatic query generation.&lt;/p&gt;

&lt;p&gt;Example: Fetch products by category or name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface ProductRepository extends JpaRepository&amp;lt;Product, Long&amp;gt; {
    List&amp;lt;Product&amp;gt; findByCategory(String category);
    List&amp;lt;Product&amp;gt; findByNameContainingIgnoreCase(String name);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Usage in Service&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List&amp;lt;Product&amp;gt; getProductsByCategory(String category) {
        return productRepository.findByCategory(category);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Spring Data JPA uses prepared statements, binding inputs like category as parameters. This ensures malicious inputs (e.g., "; DROP TABLE products; --") are treated as data, not executable SQL, preventing injection attacks.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using @Query Annotation
&lt;/h2&gt;

&lt;p&gt;The @Query annotation enables custom JPQL or native SQL queries with explicit control over the query structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.example.demo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface ProductRepository extends JpaRepository&amp;lt;Product, Long&amp;gt; {

    @Query(value = "SELECT * FROM Product WHERE stock &amp;lt; :stock", nativeQuery = true)
    List&amp;lt;Product&amp;gt; findLowStockProducts(@Param(value = "stock") Integer stock);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Usage in Service&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public List&amp;lt;Product&amp;gt; getExpensiveProducts(Double price) {
    return productRepository.findProductsAbovePrice(price);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Custom Queries with EntityManager
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;EntityManager&lt;/strong&gt; is ideal for dynamic queries where conditions vary based on runtime inputs.&lt;/p&gt;

&lt;p&gt;Example: Dynamically filter products by category and price.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import com.example.demo.model.Product;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

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

@Repository
public class CustomQuery {

    @PersistenceContext
    private EntityManager entityManager;

    public List&amp;lt;Product&amp;gt; findProductsByCriteria(String category, Double minPrice) {
        StringBuilder jpql = new StringBuilder("SELECT p FROM Product p WHERE 1=1");
        List&amp;lt;Object&amp;gt; params = new ArrayList&amp;lt;&amp;gt;();

        if (category != null) {
            jpql.append(" AND p.category = ?1");
            params.add(category);
        }
        if (minPrice != null) {
            jpql.append(" AND p.price &amp;gt;= ?").append(params.size() + 1);
            params.add(minPrice);
        }

        TypedQuery&amp;lt;Product&amp;gt; query = entityManager.createQuery(jpql.toString(), Product.class);
        for (int i = 0; i &amp;lt; params.size(); i++) {
            query.setParameter(i + 1, params.get(i));
        }

        return query.getResultList();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Practices to Avoid SQL Injection
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use parameter binding:&lt;/strong&gt; Always use prepared statements via Spring’s mechanisms or setParameter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid string concatenation:&lt;/strong&gt; Never embed user input directly into queries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validate inputs:&lt;/strong&gt; Check inputs (e.g., ensure minPrice is a number) for added safety.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Limit database permissions:&lt;/strong&gt; Restrict database roles to minimize damage from potential vulnerabilities.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Proxy Design Pattern with Caching Example in Java</title>
      <dc:creator>William</dc:creator>
      <pubDate>Sat, 02 Aug 2025 17:42:11 +0000</pubDate>
      <link>https://forem.com/wkreuch/proxy-design-pattern-with-caching-example-in-java-4f2c</link>
      <guid>https://forem.com/wkreuch/proxy-design-pattern-with-caching-example-in-java-4f2c</guid>
      <description>&lt;p&gt;Imagine an application that repeatedly queries a database for user data, causing performance bottlenecks due to slow database operations. How can we optimize this without modifying the core logic? The Proxy Design Pattern offers a solution by introducing an intermediary that controls access to the real object, enabling optimizations like caching.&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution: Proxy Pattern with Caching
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Proxy Pattern&lt;/strong&gt; introduces a Proxy class that sits between the client and the real service, adding caching to reduce database calls. We'll implement this in pure Java for simplicity, demonstrating a caching proxy for user data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Interface: UserService
public interface UserService {
    String getUserData(String userId);
}

Real Service: RealUserService
public class RealUserService implements UserService {
    @Override
    public String getUserData(String userId) {
        // Simulate a slow database query
        try {
            Thread.sleep(2000); // 2-second delay
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Data for user: " + userId;
    }
}

//Proxy Service: UserServiceProxy
import java.util.HashMap;
import java.util.Map;

public class UserServiceProxy implements UserService {
    private final UserService realUserService;
    private final Map&amp;lt;String, String&amp;gt; cache = new HashMap&amp;lt;&amp;gt;();

    public UserServiceProxy(UserService realUserService) {
        this.realUserService = realUserService;
    }

    @Override
    public String getUserData(String userId) {
        // Check cache first
        if (cache.containsKey(userId)) {
            System.out.println("Retrieved from cache: " + userId);
            return cache.get(userId);
        }
        // Fetch from real service and cache the result
        String data = realUserService.getUserData(userId);
        cache.put(userId, data);
        System.out.println("Fetched from database and cached: " + userId);
        return data;
    }
}

//Main Application
public class ProxyPatternDemo {
    public static void main(String[] args) {
        UserService realUserService = new RealUserService();
        UserService proxy = new UserServiceProxy(realUserService);

        // Test the proxy
        System.out.println(proxy.getUserData("user1")); // Hits database
        System.out.println(proxy.getUserData("user1")); // Hits cache
        System.out.println(proxy.getUserData("user2")); // Hits database
        System.out.println(proxy.getUserData("user2")); // Hits cache
    }
}

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  How It Works
&lt;/h3&gt;

&lt;p&gt;Interface: &lt;strong&gt;UserService&lt;/strong&gt; defines the contract for both the real service and the proxy.&lt;br&gt;
Real Service: &lt;strong&gt;RealUserService&lt;/strong&gt; simulates a slow database query with a 2-second delay.&lt;br&gt;
Proxy: &lt;strong&gt;UserServiceProxy&lt;/strong&gt; intercepts calls, checks a HashMap cache, and only calls &lt;strong&gt;RealUserService&lt;/strong&gt; if the data isn't cached.&lt;br&gt;
Main Class: Demonstrates the proxy in action, showing how repeated requests leverage the cache.&lt;/p&gt;

&lt;p&gt;When you run, the first call to &lt;strong&gt;getUserData("user1")&lt;/strong&gt; hits the database (slow), but subsequent calls for the same userId retrieve data from the cache (fast).&lt;/p&gt;

&lt;h3&gt;
  
  
  Benefits
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Performance&lt;/strong&gt;: Caching reduces database calls, improving response times.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transparency&lt;/strong&gt;: The client uses the same interface, unaware of the proxy.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extensibility&lt;/strong&gt;: The proxy can be extended for additional features like logging or access control.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;The Proxy Pattern elegantly solves the problem of inefficient database access by introducing a caching layer without altering the core service. In this Java example, we used a simple HashMap for caching, significantly improving performance for repeated requests.&lt;br&gt;
In a real-world project, caching approaches would be more robust like Redis.&lt;/p&gt;

&lt;p&gt;Additionally, the Proxy Pattern is versatile beyond caching. It can be used for logging, capturing method calls, parameters, and execution times for debugging or auditing. For example, you could extend UserServiceProxy to log each request to a file or monitoring system, enhancing observability without changing the core service logic. This makes the Proxy Pattern a powerful tool for optimizing and extending system behavior transparently.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>The Decorator Pattern in Java</title>
      <dc:creator>William</dc:creator>
      <pubDate>Sat, 02 Aug 2025 17:04:51 +0000</pubDate>
      <link>https://forem.com/wkreuch/the-decorator-pattern-in-java-3n4</link>
      <guid>https://forem.com/wkreuch/the-decorator-pattern-in-java-3n4</guid>
      <description>&lt;p&gt;Imagine you need to display text with various formatting options, like bold or italic, but you want to keep the core text-display logic unchanged. Modifying the base class for each new style can quickly become messy and violate the Open-Closed Principle. How do we add functionality dynamically without altering existing code? The Decorator Pattern is the answer!&lt;/p&gt;

&lt;h2&gt;
  
  
  Solution: The Decorator Pattern
&lt;/h2&gt;

&lt;p&gt;The Decorator Pattern allows us to wrap a core component with additional responsibilities dynamically. In Java, this is achieved using an interface, a base component, and decorator classes that implement the same interface while holding a reference to the component they enhance. This enables stacking behaviors without modifying the original object.&lt;br&gt;
Below is a practical example in Java demonstrating the Decorator Pattern to add text formatting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Component Interface
interface Text {
    String display();
}

// Concrete Component
class SimpleText implements Text {
    private String content;

    public SimpleText(String content) {
        this.content = content;
    }

    @Override
    public String display() {
        return content;
    }
}

// Abstract Decorator Class
abstract class TextDecorator implements Text {
    protected Text decoratedText;

    public TextDecorator(Text decoratedText) {
        this.decoratedText = decoratedText;
    }

    @Override
    public String display() {
        return decoratedText.display();
    }
}

// Concrete Decorator: Bold
class BoldTextDecorator extends TextDecorator {
    public BoldTextDecorator(Text decoratedText) {
        super(decoratedText);
    }

    @Override
    public String display() {
        return "&amp;lt;b&amp;gt;" + super.display() + "&amp;lt;/b&amp;gt;";
    }
}

// Concrete Decorator: Italic
class ItalicTextDecorator extends TextDecorator {
    public ItalicTextDecorator(Text decoratedText) {
        super(decoratedText);
    }

    @Override
    public String display() {
        return "&amp;lt;i&amp;gt;" + super.display() + "&amp;lt;/i&amp;gt;";
    }
}

// Demo Class
public class DecoratorPatternDemo {
    public static void main(String[] args) {
        Text simpleText = new SimpleText("Hello, World!");
        Text boldText = new BoldTextDecorator(simpleText);
        Text italicText = new ItalicTextDecorator(simpleText);
        Text boldItalicText = new BoldTextDecorator(new ItalicTextDecorator(simpleText));

        System.out.println("Plain Text: " + simpleText.display());
        System.out.println("Bold Text: " + boldText.display());
        System.out.println("Italic Text: " + italicText.display());
        System.out.println("Bold and Italic Text: " + boldItalicText.display());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;Text&lt;/strong&gt; interface defines the core operation (display()).&lt;br&gt;
&lt;strong&gt;SimpleText&lt;/strong&gt; is the concrete component that holds the base text.&lt;br&gt;
&lt;strong&gt;TextDecorator&lt;/strong&gt; is an abstract class that implements Text and holds a reference to a Text object via its constructor.&lt;br&gt;
Concrete decorators (&lt;strong&gt;BoldTextDecorator&lt;/strong&gt;, &lt;strong&gt;ItalicTextDecorator&lt;/strong&gt;) extend &lt;strong&gt;TextDecorator&lt;/strong&gt; to add specific formatting.&lt;br&gt;
The main method shows how decorators can be stacked to combine behaviors (e.g., bold + italic).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Output:
Plain Text: Hello, World!
Bold Text: &amp;lt;b&amp;gt;Hello, World!&amp;lt;/b&amp;gt;
Italic Text: &amp;lt;i&amp;gt;Hello, World!&amp;lt;/i&amp;gt;
Bold and Italic Text: &amp;lt;b&amp;gt;&amp;lt;i&amp;gt;Hello, World!&amp;lt;/i&amp;gt;&amp;lt;/b&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;The &lt;strong&gt;Decorator Pattern&lt;/strong&gt; solves the problem of adding responsibilities to objects flexibly and reusably. By using an interface and passing the component through the decorator’s constructor, we can stack behaviors dynamically without modifying the core class. This approach adheres to the Open-Closed Principle and makes the system extensible for future enhancements, like adding new decorators for underlining or colors. Try it out in your Java projects to keep your code clean and modular!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Strategy Design Pattern</title>
      <dc:creator>William</dc:creator>
      <pubDate>Mon, 21 Jul 2025 02:07:31 +0000</pubDate>
      <link>https://forem.com/wkreuch/strategy-design-pattern-4i2c</link>
      <guid>https://forem.com/wkreuch/strategy-design-pattern-4i2c</guid>
      <description>&lt;p&gt;Imagine you are building an e-commerce platform, and you need to handle multiple payment methods like credit cards, PayPal, and bank transfers. Each method has its own processing logic, but you want to keep your code flexible and maintainable.&lt;br&gt;
How do you manage these different payment methods without cluttering your code with conditionals? The &lt;strong&gt;Strategy Design Pattern&lt;/strong&gt; is the solution, allowing you to define a family of algorithms, encapsulate each one, and make them interchangeable.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Strategy Pattern?
&lt;/h2&gt;

&lt;p&gt;The Strategy Pattern is a behavioral design pattern that enables you to define a set of algorithms, encapsulate them in separate classes, and switch between them dynamically. This makes your code more modular, easier to extend, and avoids hard-coded logic.&lt;/p&gt;

&lt;h2&gt;
  
  
  Code Example
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Strategy Interface
interface PaymentStrategy {
    boolean processPayment(double amount);
}

// Concrete Strategy: Credit Card
class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing credit card payment of $" + amount);
        // Simulate card validation and API call
        return true;
    }
}

// Concrete Strategy: PayPal
class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public boolean processPayment(double amount) {
        System.out.println("Processing PayPal payment of $" + amount);
        // Simulate PayPal API call
        return true;
    }
}

// Context Class
class PaymentProcessor {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public boolean process(double amount) {
        if (paymentStrategy == null) {
            throw new IllegalStateException("Payment strategy not set");
        }
        return paymentStrategy.processPayment(amount);
    }
}

// Usage Example
public class Main {
    public static void main(String[] args) {
        PaymentProcessor processor = new PaymentProcessor();

        // Paying with Credit Card
        processor.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
        processor.process(100.0);

        // Switching to PayPal
        processor.setPaymentStrategy(new PayPalPayment("user@example.com"));
        processor.process(50.0);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The &lt;strong&gt;PaymentStrategy interface&lt;/strong&gt; defines the contract for all payment methods.&lt;/li&gt;
&lt;li&gt;Each concrete strategy (&lt;strong&gt;CreditCardPayment, PayPalPayment&lt;/strong&gt;) encapsulates its own logic.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;PaymentProcessor&lt;/strong&gt; context class delegates the payment processing to the current strategy.&lt;/li&gt;
&lt;li&gt;At runtime, you can swap strategies (e.g., switch from Credit Card to PayPal) without modifying the &lt;strong&gt;PaymentProcessor&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Benefits
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Flexibility:&lt;/strong&gt; Add new payment methods by creating new strategy classes without changing existing code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Maintainability:&lt;/strong&gt; Each payment method is encapsulated, reducing code complexity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reusability:&lt;/strong&gt; Strategies can be reused across different contexts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Strategy Pattern solves the problem of handling multiple payment methods by making them interchangeable and encapsulated. By using this pattern, your e-commerce platform can easily support new payment methods, keeping your codebase clean and scalable.&lt;/p&gt;

</description>
      <category>java</category>
      <category>designpatterns</category>
      <category>programming</category>
    </item>
    <item>
      <title>Spring Cloud Function</title>
      <dc:creator>William</dc:creator>
      <pubDate>Tue, 15 Jul 2025 01:02:07 +0000</pubDate>
      <link>https://forem.com/wkreuch/spring-cloud-function-1i1d</link>
      <guid>https://forem.com/wkreuch/spring-cloud-function-1i1d</guid>
      <description>&lt;p&gt;Imagine you're building a microservices architecture, and you need a lightweight, flexible way to handle business logic without being tied to specific server frameworks or deployment models. The problem? Traditional approaches often involve heavy boilerplate code and rigid configurations, making development and deployment complex. Spring Cloud Function solves this by providing a functional programming model for building cloud-native applications. Let’s explore what it is, what problems it solves, where it’s used, and a simple example.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Spring Cloud Function?
&lt;/h2&gt;

&lt;p&gt;Spring Cloud Function is a framework within the Spring ecosystem that enables developers to write business logic as functions—simple, reusable, and stateless units of code. It abstracts away the underlying infrastructure, allowing you to deploy functions to various platforms, such as serverless environments (e.g., AWS Lambda, Azure Functions) or traditional servers, with minimal configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What Problems Does It Solve?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Simplifies Development:&lt;/strong&gt; It reduces boilerplate code by letting you focus on writing pure functions (e.g., Function), decoupled from web frameworks or server concerns.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Platform Flexibility:&lt;/strong&gt; Functions can be deployed to serverless platforms, Kubernetes, or traditional servers without code changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-Driven Architecture:&lt;/strong&gt; It seamlessly integrates with event streams (e.g., Kafka, RabbitMQ), making it ideal for reactive, event-driven systems.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scalability:&lt;/strong&gt; Functions are stateless, enabling easy scaling in cloud environments.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Spring Cloud Function is used in:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Serverless Applications:&lt;/strong&gt; Deploying lightweight functions to AWS Lambda, Azure Functions, or Google Cloud Functions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Microservices:&lt;/strong&gt; Handling specific tasks in distributed systems.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-Driven Systems:&lt;/strong&gt; Processing messages from Kafka, RabbitMQ, or other message brokers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enterprise Applications:&lt;/strong&gt; Simplifying business logic in Spring-based projects, especially in cloud-native environments.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Dependencies
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-cloud-starter-function-web&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;4.1.3&amp;lt;/version&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Basic Example
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.function.Function;

@SpringBootApplication
public class SquareFunctionApplication {

    @Bean
    public Function&amp;lt;Integer, Integer&amp;gt; square() {
        return number -&amp;gt; number * number;
    }

    public static void main(String[] args) {
        SpringApplication.run(SquareFunctionApplication.class, args);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The square function takes an Integer input and returns its square using a lambda expression (number -&amp;gt; number * number).&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Bean&lt;/strong&gt; annotation registers the function with Spring’s context.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;spring-cloud-starter-function-web&lt;/strong&gt; dependency enables HTTP support for local testing or serverless deployment.&lt;/li&gt;
&lt;li&gt;To test locally, run the application and send a POST request to &lt;strong&gt;&lt;a href="http://localhost:8080/square" rel="noopener noreferrer"&gt;http://localhost:8080/square&lt;/a&gt;&lt;/strong&gt; with a JSON payload like 5. The response will be 25.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fenzgadagwnriqupvlvbw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fenzgadagwnriqupvlvbw.png" alt="call in Postman" width="800" height="207"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For serverless deployment, configure the function for platforms like AWS Lambda using Spring Cloud Function’s adapters.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;Spring Cloud Function tackles the challenge of building scalable, lightweight applications by letting developers write business logic as functions. It simplifies development, supports flexible deployments, and integrates with event-driven systems. The square calculation example demonstrates how to process numerical data in a reusable, deployable function. By using Spring Cloud Function, you can streamline microservices or serverless projects, solving complexity and boosting productivity.&lt;br&gt;
&lt;a href="https://spring.io/projects/spring-cloud-function." rel="noopener noreferrer"&gt;See more in the official documentation&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>sprincloud</category>
      <category>microservices</category>
    </item>
    <item>
      <title>Advanced Use of Predicate, Function, Consumer, and Comparator in Java</title>
      <dc:creator>William</dc:creator>
      <pubDate>Tue, 15 Jul 2025 00:28:49 +0000</pubDate>
      <link>https://forem.com/wkreuch/advanced-use-of-predicate-function-consumer-and-comparator-in-java-3dim</link>
      <guid>https://forem.com/wkreuch/advanced-use-of-predicate-function-consumer-and-comparator-in-java-3dim</guid>
      <description>&lt;p&gt;Suppose you are building a Java application to manage a product inventory. You need to filter products by category, transform them into a formatted report, perform actions like logging, and sort them by price. Traditionally, this requires verbose loops and anonymous classes, leading to code that's hard to read and maintain. How can we handle this elegantly? Java’s functional interfaces: &lt;strong&gt;Predicate, Function, Consumer, and Comparator&lt;/strong&gt;, combined with lambda expressions and the Stream API, provide a concise, functional solution.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example Scenario
&lt;/h2&gt;

&lt;p&gt;Imagine a &lt;strong&gt;Product&lt;/strong&gt; class with name, category, and price.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Product {
    private String name;
    private String category;
    private double price;

    public Product(String name, String category, double price) {
        this.name = name;
        this.category = category;
        this.price = price;
    }

    public String getName() { return name; }
    public String getCategory() { return category; }
    public double getPrice() { return price; }

    @Override
    public String toString() {
        return name + " (" + category + ", $" + price + ")";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We want to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Filter products in the "Electronics" category with a price above $100.&lt;/li&gt;
&lt;li&gt;Transform each product into a formatted report string.&lt;/li&gt;
&lt;li&gt;Log each processed product to a list.&lt;/li&gt;
&lt;li&gt;Sort the results by price in descending order.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Solution
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ProductDemo {
    public static void main(String[] args) {

        List&amp;lt;Product&amp;gt; products = Arrays.asList(
                new Product("Phone", "Electronics", 499.99),
                new Product("Laptop", "Electronics", 999.99),
                new Product("Desk", "Furniture", 150.00),
                new Product("Headphones", "Electronics", 89.99),
                new Product("Tablet", "Electronics", 299.99)
        );


        Predicate&amp;lt;Product&amp;gt; isExpensiveElectronics = p -&amp;gt;
                p.getCategory().equals("Electronics") &amp;amp;&amp;amp; p.getPrice() &amp;gt; 100;

        Function&amp;lt;Product, String&amp;gt; formatReport = p -&amp;gt;
                String.format("Product: %s, Price: $%.2f", p.getName(), p.getPrice());

        List&amp;lt;String&amp;gt; log = new ArrayList&amp;lt;&amp;gt;();
        Consumer&amp;lt;Product&amp;gt; logProduct = p -&amp;gt; log.add("Processed: " + p);

        Comparator&amp;lt;Product&amp;gt; byPriceDesc = (p1, p2) -&amp;gt;
                Double.compare(p2.getPrice(), p1.getPrice());


        List&amp;lt;String&amp;gt; report = products.stream()
                .filter(isExpensiveElectronics)
                .peek(logProduct)
                .sorted(byPriceDesc)
                .map(formatReport)
                .toList();

        System.out.println("Formatted Report:");
        report.forEach(System.out::println);

        System.out.println("\nAudit Log:");
        log.forEach(System.out::println);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Explanation of the Code
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Predicate: &lt;strong&gt;isExpensiveElectronics&lt;/strong&gt;combines two conditions (category and price) to filter electronics over $100.&lt;/li&gt;
&lt;li&gt;Function: &lt;strong&gt;formatReport&lt;/strong&gt; transforms each product into a formatted string for the report.&lt;/li&gt;
&lt;li&gt;Consumer: &lt;strong&gt;logProduct&lt;/strong&gt; adds each filtered product to an audit log using peek.&lt;/li&gt;
&lt;li&gt;Comparator: &lt;strong&gt;byPriceDesc&lt;/strong&gt; sorts products by price in descending order.&lt;/li&gt;
&lt;li&gt;Stream Pipeline: Chains filter, peek, sorted, and map to process the list at once.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Formatted Report:
Product: Laptop, Price: $999.99
Product: Phone, Price: $499.99
Product: Tablet, Price: $299.99

Audit Log:
Processed: Laptop (Electronics, $999.99)
Processed: Phone (Electronics, $499.99)
Processed: Tablet (Electronics, $299.99)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;Predicate, Function, Consumer, and Comparator address the challenge of complex data processing by enabling a concise, functional pipeline. In this inventory example, they filtered, transformed, logged, and sorted products efficiently, reducing boilerplate compared to traditional loops and classes. With no external dependencies and tight integration with Java’s Stream API, these interfaces make code modular, readable, and maintainable, solving real-world data processing problems in modern Java applications.&lt;/p&gt;

</description>
      <category>java</category>
      <category>lambda</category>
    </item>
    <item>
      <title>The Builder Design Pattern in Java</title>
      <dc:creator>William</dc:creator>
      <pubDate>Thu, 10 Jul 2025 02:07:53 +0000</pubDate>
      <link>https://forem.com/wkreuch/the-builder-design-pattern-in-java-167l</link>
      <guid>https://forem.com/wkreuch/the-builder-design-pattern-in-java-167l</guid>
      <description>&lt;p&gt;Creating complex objects, like a custom Car, often involves juggling multiple attributes: engine, wheels, color, etc. Using a single constructor with many parameters is cumbersome and error-prone. How can we build such objects cleanly and flexibly? The Builder Design Pattern in Java provides a solution by separating the construction process from the object's representation, enabling step-by-step assembly.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Builder Pattern?
&lt;/h2&gt;

&lt;p&gt;The Builder Pattern is a creational design pattern that constructs complex objects incrementally using a dedicated Builder class. This approach improves code readability, supports flexible configurations, and avoids bloated constructors.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example in Java
&lt;/h2&gt;

&lt;p&gt;Below is a Java implementation of the Builder Pattern for building a car object:&lt;/p&gt;

&lt;p&gt;Create Car class.&lt;br&gt;
&lt;/p&gt;

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

    private String engine;
    private int wheels;
    private String color;

    private Car() {}

    protected Car(CarBuilder builder) {
        this.engine = builder.engine;
        this.wheels = builder.wheels;
        this.color = builder.color;
    }

    @Override
    public String toString() {
        return "Car with " + engine + " engine, " + wheels + " wheels, and " + color + " color";
    }

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

&lt;/div&gt;



&lt;p&gt;Create CarBuilder class in the same package of Car.&lt;br&gt;
&lt;/p&gt;

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

    protected String engine;
    protected int wheels;
    protected String color;

    public CarBuilder setEngine(String engine) {
        this.engine = engine;
        return this;
    }

    public CarBuilder setWheels(int wheels) {
        this.wheels = wheels;
        return this;
    }

    public CarBuilder setColor(String color) {
        this.color = color;
        return this;
    }

    public Car build() {
        return new Car(this);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use CarBuilder to return a instance of Car.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main { 
    public static void main(String[] args) { 
        Car car = new CarBuilder()
                .setEngine("V8")
                .setWheels(4)
                .setColor("Red")
                .build();
        System.out.println(car); 
        // Output: Car with V8 engine, 4 wheels, and Red color 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Advantages of the Builder Pattern
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Readability&lt;/strong&gt;: Method chaining creates a clear, fluent API for object construction.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flexibility&lt;/strong&gt;: Easily add or omit optional attributes without modifying the core class.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Immutability&lt;/strong&gt;: The Car object is immutable, as all fields are final, enhancing thread safety.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Separation of Concerns&lt;/strong&gt;: Construction logic is isolated in the Builder, keeping the Car class focused on its data.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Disadvantages of the Builder Pattern
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Increased Code&lt;/strong&gt;: Requires a separate Builder class, adding boilerplate code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Overkill for Simple Objects&lt;/strong&gt;: For objects with few attributes, the pattern may be unnecessarily complex.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Maintenance&lt;/strong&gt;: Changes to the Car class (e.g., adding new fields) require corresponding updates to the Builder.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Spring Boot Example with Builder
&lt;/h2&gt;

&lt;p&gt;In Spring Boot, the Builder Pattern is commonly used in configuration classes. Below is an example of a &lt;strong&gt;RestTemplate configuration&lt;/strong&gt; using a custom &lt;strong&gt;RestTemplateBuilder&lt;/strong&gt; to configure HTTP client settings:&lt;br&gt;
&lt;/p&gt;

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(5))
                .setReadTimeout(Duration.ofSeconds(10))
                .build();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;p&gt;The Builder Pattern in Java, including in Spring Boot, solves the problem of constructing complex objects by providing a clean, step-by-step approach. Whether building a Car or configuring a RestTemplate, it ensures readability, flexibility, and maintainability. While it introduces some code overhead, its benefits make it invaluable for complex systems, especially in Spring Boot applications where configuration objects are common.&lt;/p&gt;

</description>
      <category>java</category>
      <category>designpatterns</category>
      <category>springboot</category>
      <category>programming</category>
    </item>
    <item>
      <title>Creating an API Gateway with Spring Boot</title>
      <dc:creator>William</dc:creator>
      <pubDate>Mon, 07 Jul 2025 02:54:33 +0000</pubDate>
      <link>https://forem.com/wkreuch/creating-an-api-gateway-with-spring-boot-52ab</link>
      <guid>https://forem.com/wkreuch/creating-an-api-gateway-with-spring-boot-52ab</guid>
      <description>&lt;p&gt;An API Gateway acts as a single entry point for client requests, routing them to appropriate backend services. It simplifies client interactions, enhances security, and provides features like load balancing, authentication, and monitoring.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is an API Gateway and Why Use It?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An API Gateway(design pattern) is a server that handles incoming API requests and directs them to the relevant microservices. It serves as a reverse proxy, abstracting the complexity of a microservices architecture. Common use cases include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Routing&lt;/strong&gt;: Directing requests to the correct service.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication/Authorization&lt;/strong&gt;: Centralizing security checks.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rate Limiting&lt;/strong&gt;: Controlling request volumes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Monitoring&lt;/strong&gt;: Tracking API usage and performance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Pros of Using an API Gateway
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Simplifies client-side code by providing a unified interface.&lt;/li&gt;
&lt;li&gt;Centralizes cross-cutting concerns like security and logging.&lt;/li&gt;
&lt;li&gt;Improves scalability by distributing requests efficiently.&lt;/li&gt;
&lt;li&gt;Enhances maintainability by decoupling clients from services.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  API Gateway with Spring Boot
&lt;/h2&gt;

&lt;p&gt;Spring Boot, combined with Spring Cloud Gateway, is a powerful choice for building an API Gateway due to its simplicity and robust ecosystem. Below, we’ll walk through the setup, including Maven dependencies and basic configuration.&lt;br&gt;
The version of spring boot will be &lt;strong&gt;3.4.3&lt;/strong&gt; and spring cloud &lt;strong&gt;2024.0.1&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Maven Dependencies&lt;/strong&gt;&lt;br&gt;
To get started, create a Spring Boot project and include the necessary dependencies in your &lt;strong&gt;pom.xml.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-cloud-starter-gateway&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.cloud&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-cloud-starter-netflix-eureka-client&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-actuator&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Basic Configuration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Configure the API Gateway in the &lt;strong&gt;application.yml&lt;/strong&gt; file and Eureka Server.&lt;/p&gt;

&lt;p&gt;Information about the port, application name and Eureka server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server:
  port: 8080
spring:
  application:
    name: api-gateway
eureka:
  instance:
    preferIpAddress: true
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
    fetch-registry: true
    register-with-eureka: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To exposes actuator endpoints for monitoring:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;management:
  endpoints:
    web:
      exposure:
        include: health,info,gateway
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Route&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a &lt;strong&gt;Bean RouterLocator&lt;/strong&gt; to configure the route from Api Gateway to microservice, is possible to configure your circuit break and Header here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Bean
public RouteLocator routeConfig(RouteLocatorBuilder routeLocatorBuilder) {
    return routeLocatorBuilder.routes()
            .route(p -&amp;gt; p
                    .path("/&amp;lt;PATH_FROM_CLIENT&amp;gt;/**")
                    .filters( f -&amp;gt; f.rewritePath("/&amp;lt;PATH_FROM_CLIENT&amp;gt;/(?&amp;lt;segment&amp;gt;.*)","/${segment}")
                            .addResponseHeader("X-Response-Time", LocalDateTime.now().toString())
                    .uri("lb://&amp;lt;MICROSERVICE_APP_NAME&amp;gt;"))
            .build();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;PATH_FROM_CLIENT&lt;/strong&gt;: Inform the path that clients will call&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MICROSERVICE_APP_NAME&lt;/strong&gt;: Inform &lt;em&gt;spring.application.name&lt;/em&gt; of the microservice of destination.
With the help of Eureka Server, API Gateway will find the given microservice.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this post the microservice name will be &lt;em&gt;client-service&lt;/em&gt; and path &lt;em&gt;client-service&lt;/em&gt;, but could be any value you desire.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Test&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With the &lt;strong&gt;Bean RouteLocator&lt;/strong&gt; now all request send to &lt;strong&gt;/client-service/&lt;/strong&gt;** will be redirect to microservice called client-service.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flyqqx4gdc3mblppgud11.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flyqqx4gdc3mblppgud11.png" alt="Postman Request Api-Gateway" width="800" height="232"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you test request direct to client-service, not using API Gateway, will have the same result.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fomyotyk68umjeiwgee09.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fomyotyk68umjeiwgee09.png" alt="Postman Request Client-Service" width="800" height="196"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the production application, the client service will be exposed only in the private network, and only through the Api Gateway will it be exposed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;An API Gateway is a vital component in a microservices architecture, simplifying client interactions and centralizing concerns like routing and security. With Spring Boot and Spring Cloud Gateway, setting up a basic API Gateway is straightforward, requiring minimal dependencies and configuration.&lt;br&gt;
By following the steps above, you can quickly create a gateway to route requests to your services, paving the way for advanced features like authentication and rate limiting in future iterations.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>apigateway</category>
      <category>designpatterns</category>
      <category>programming</category>
    </item>
    <item>
      <title>Build optimized Docker images with JIB Maven Plugin</title>
      <dc:creator>William</dc:creator>
      <pubDate>Tue, 01 Jul 2025 13:30:00 +0000</pubDate>
      <link>https://forem.com/wkreuch/create-optimized-docker-images-with-jib-maven-plugin-1cim</link>
      <guid>https://forem.com/wkreuch/create-optimized-docker-images-with-jib-maven-plugin-1cim</guid>
      <description>&lt;p&gt;&lt;strong&gt;Jib&lt;/strong&gt; is a plugin that builds optimized Docker images for &lt;strong&gt;Java&lt;/strong&gt; applications. It organizes image layers efficiently, separating dependencies, resources, and application code, which &lt;strong&gt;reduces image size&lt;/strong&gt; and &lt;strong&gt;speeds up rebuilds.&lt;/strong&gt; with Maven, Jib is configured in the &lt;strong&gt;pom.xml&lt;/strong&gt; file, enabling seamless integration into the build lifecycle.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it works:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Project analysis:&lt;/strong&gt; Jib reads the pom.xml to identify dependencies, classes, and resources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Image building:&lt;/strong&gt; Creates optimized layers (dependencies, resources, classes) and assembles the Docker image.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Publishing (optional):&lt;/strong&gt; Pushes the image to a configured registry, such as Docker Hub.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Local execution (optional):&lt;/strong&gt; Can run the image locally if Docker is available.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Jib doesn’t require a Dockerfile but allows customization through the pom.xml. It supports fast builds with reusable layers and is ideal for CI/CD pipelines.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advantages of Jib with Maven
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;No Dockerfile: Simple configuration in pom.xml.&lt;/li&gt;
&lt;li&gt;Fast builds: Reuses unchanged layers.&lt;/li&gt;
&lt;li&gt;Portability: Doesn’t depend on a local Docker daemon.&lt;/li&gt;
&lt;li&gt;Security: Supports authentication for private registries.&lt;/li&gt;
&lt;li&gt;CI/CD integration: Compatible with tools like Jenkins and GitHub Actions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Basic Configuration Example
&lt;/h2&gt;

&lt;p&gt;Let’s set up Jib in a Maven project to create a Docker image for a simple Spring Boot application and publish it to Docker Hub.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Maven project with Java (Spring Boot).&lt;/li&gt;
&lt;li&gt;Docker Hub account (for publishing).&lt;/li&gt;
&lt;li&gt;Maven installed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Configure the pom.xml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;project&amp;gt;
  ...
  &amp;lt;build&amp;gt;
    &amp;lt;plugins&amp;gt;
      &amp;lt;plugin&amp;gt;
        &amp;lt;groupId&amp;gt;com.google.cloud.tools&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;jib-maven-plugin&amp;lt;/artifactId&amp;gt;
        &amp;lt;version&amp;gt;3.4.3&amp;lt;/version&amp;gt;
        &amp;lt;configuration&amp;gt;
          &amp;lt;from&amp;gt;
            &amp;lt;image&amp;gt;openjdk:17-jdk-slim&amp;lt;/image&amp;gt;
          &amp;lt;/from&amp;gt;
          &amp;lt;to&amp;gt;
&amp;lt;image&amp;gt;docker.io/youruser/${project.artifactId}:${project.version}&amp;lt;/image&amp;gt;
          &amp;lt;/to&amp;gt;
        &amp;lt;/configuration&amp;gt;
      &amp;lt;/plugin&amp;gt;
    &amp;lt;/plugins&amp;gt;
  &amp;lt;/build&amp;gt;
&amp;lt;/project&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;from:&lt;/strong&gt; Specifies the base image (here, openjdk:17-jdk-slim).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;to:&lt;/strong&gt; Defines the generated image name and registry (replace youruser with your Docker Hub username).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Build the Image&lt;/p&gt;

&lt;p&gt;Run the Maven command to build the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mvn compile jib:build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This compiles the project and builds the Docker image, pushing it directly to Docker Hub. If authentication isn’t configured, log in to Docker Hub.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Test Locally (Optional)&lt;/p&gt;

&lt;p&gt;To build the image without pushing to a registry, use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mvn compile jib:dockerBuild
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, run the image with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker run -p 8080:8080 youruser/my-app:latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Jib streamlines Docker image creation for Java projects, integrating seamlessly with Maven to build and publish optimized images without Dockerfiles. Its simplicity and efficiency make it ideal for both small projects and complex CI/CD pipelines. Start using Jib to enhance your development workflow! 🚀&lt;/p&gt;

&lt;p&gt;Official documentation: &lt;a href="https://github.com/GoogleContainerTools/jib" rel="noopener noreferrer"&gt;https://github.com/GoogleContainerTools/jib&lt;/a&gt;&lt;/p&gt;

</description>
      <category>java</category>
      <category>docker</category>
      <category>springboot</category>
      <category>programming</category>
    </item>
    <item>
      <title>@Valid + Jakarta with DTO in Spring Boot 3</title>
      <dc:creator>William</dc:creator>
      <pubDate>Thu, 25 Jan 2024 03:28:42 +0000</pubDate>
      <link>https://forem.com/wkreuch/valid-jakarta-with-dto-in-spring-boot-3-260</link>
      <guid>https://forem.com/wkreuch/valid-jakarta-with-dto-in-spring-boot-3-260</guid>
      <description>&lt;p&gt;Every API REST need validations, and to resolve the initial situations, can be use jakarta to help us to do it fast and don't necessarily create a IF for each atribute.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add dependency
&lt;/h2&gt;

&lt;p&gt;In the pom.xml put this new dependency to use jakarta.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Implement validations in DTO
&lt;/h2&gt;

&lt;p&gt;In the DTO class, in this case only in record ProductCreateUpdate, put the annotations from jakarta before each variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.spring.models.dto;

import jakarta.validation.constraints.*;

public record ProductCreateUpdate(@NotBlank @Size(min = 2, max = 125) String name, @PositiveOrZero Double price, @Size(max = 500) String description) {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The annotations is not difficult understand, the name of each means what to do, it's possible use a combination in only one. You can figure out all annotations in this &lt;a href="https://jakarta.ee/specifications/bean-validation/3.0/apidocs/jakarta/validation/constraints/package-summary" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For this validation to be used when receiving the body, it's necessary to use the &lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt;&lt;/strong&gt; annotation in the controller method declaration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import jakarta.validation.Valid;
public class ProductController {
[...]
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;Product&amp;gt; create(@RequestBody @Valid ProductCreateUpdate productCreate) {
        Product product = new Product();
        BeanUtils.copyProperties(productCreate, product);

        return ResponseEntity.status(HttpStatus.CREATED).body(service.create(product));
    }

    @PutMapping(path = "/{id}",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;Product&amp;gt; update(@PathVariable(value = "id") Long id, @RequestBody @Valid ProductCreateUpdate productUpdate) {
        Product product = new Product();
        BeanUtils.copyProperties(productUpdate, product);

        return ResponseEntity.status(HttpStatus.OK).body(service.update(product, id));
    }
[...]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How the body is of type &lt;strong&gt;ProductCreateUpdate&lt;/strong&gt;, so put &lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt;&lt;/strong&gt; before the body declaration. The validation is necessary only in the &lt;strong&gt;POST&lt;/strong&gt; e &lt;strong&gt;PUT&lt;/strong&gt; request, the validation will work equal for both.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handle validation exception
&lt;/h2&gt;

&lt;p&gt;To made the response of error look better when the data received is wrong, let's create a method to handle the &lt;strong&gt;MethodArgumentNotValidException&lt;/strong&gt; in &lt;strong&gt;CustomizedResponseEntityExceptionHandler&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomizedResponseEntityExceptionHandler {
[...]
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public final ResponseEntity&amp;lt;ExceptionResponse&amp;gt; handlerMethodArgumentValidExceptions(MethodArgumentNotValidException exception, WebRequest request) {
        var errors = exception.getFieldErrors().stream().map(fieldError -&amp;gt; "Field: " + fieldError.getField() + " Error: " + fieldError.getDefaultMessage()).toList();
        ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now(), errors.toString(), request.getDescription(false));

        return new ResponseEntity&amp;lt;&amp;gt;(exceptionResponse, HttpStatus.BAD_REQUEST);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The method will take each message error from the list and put everything into a custom message.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;In the postman make this request to create a Product.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;POST localhost:8080/api/product&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "name": "",
    "price": -50.00,
    "description": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaA"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foh1md19gu57yp9e7e84m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foh1md19gu57yp9e7e84m.png" alt="post" width="800" height="455"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This test is to show all valiton working, look that the response code is &lt;strong&gt;400 Bad Request&lt;/strong&gt; and in the response, the message is easy to read and understand what is necessary to resolve.&lt;/p&gt;

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

&lt;p&gt;In this post, we create a validation using only annotations by jakarta and that have many options to implement for each situation. Jakarta can be use to valid String, number, date, booleans...&lt;/p&gt;

&lt;h2&gt;
  
  
  Next Step
&lt;/h2&gt;

&lt;p&gt;In the next step we will use Swagger to create a documentation about the API.&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>spring</category>
      <category>restapi</category>
    </item>
    <item>
      <title>Using ResponseEntity with global exception handling in Spring Boot 3</title>
      <dc:creator>William</dc:creator>
      <pubDate>Fri, 19 Jan 2024 01:48:35 +0000</pubDate>
      <link>https://forem.com/wkreuch/using-responseentity-with-global-exception-handling-in-spring-boot-3-3fm6</link>
      <guid>https://forem.com/wkreuch/using-responseentity-with-global-exception-handling-in-spring-boot-3-3fm6</guid>
      <description>&lt;p&gt;Now that we already have one  REST API working, let's improving with using a better response code and control all exception with a global class.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create a global class to handle exceptions
&lt;/h2&gt;

&lt;p&gt;First create a record class &lt;strong&gt;ExceptionResponse&lt;/strong&gt; inside the new folder &lt;strong&gt;exceptions&lt;/strong&gt; to return information about errors that occurred.&lt;br&gt;
&lt;/p&gt;

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

import java.time.Instant;

public record ExceptionResponse(Instant data, String message, String details) {
}

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

&lt;/div&gt;



&lt;p&gt;This record has a variable to return the instant that error occurred, and a message with details.&lt;/p&gt;

&lt;p&gt;Now let's create a expeception &lt;strong&gt;ResourceNotFoundException&lt;/strong&gt; &lt;br&gt;
inside the folder &lt;strong&gt;exceptions&lt;/strong&gt; to use when it isn't find a specific entity, in this case a Product.&lt;br&gt;
&lt;/p&gt;

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

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String messageError) {
        super(messageError);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;@ResponseStatus&lt;/strong&gt; annotation are used to inform the default return code for that exception, in this case &lt;strong&gt;NOT_FOUND&lt;/strong&gt; = 404.&lt;/p&gt;

&lt;p&gt;To finish this part, it's necessary create a global class, create a class &lt;strong&gt;CustomizedResponseEntityExceptionHandler&lt;/strong&gt; inside the folder &lt;strong&gt;exceptions&lt;/strong&gt; a new folder &lt;strong&gt;handler&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.spring.exceptions.handler;

import com.spring.exceptions.ExceptionResponse;
import com.spring.exceptions.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

import java.time.Instant;

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity&amp;lt;ExceptionResponse&amp;gt; handlerAllExceptions(Exception exception, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now(), exception.getMessage(), request.getDescription(false));
        return new ResponseEntity&amp;lt;&amp;gt;(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public final ResponseEntity&amp;lt;ExceptionResponse&amp;gt; handlerNotFoundExceptions(Exception exception, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(Instant.now(), exception.getMessage(), request.getDescription(false));
        return new ResponseEntity&amp;lt;&amp;gt;(exceptionResponse, HttpStatus.NOT_FOUND);
    }

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

&lt;/div&gt;



&lt;p&gt;This class is using the &lt;strong&gt;@ControllerAdvice&lt;/strong&gt; annotation to deal with all exceptions in the app, it's a way to control in only one place. In this part you decide with is better to control case a case or all in one.&lt;br&gt;
This class is a Controller because use &lt;strong&gt;@RestController&lt;/strong&gt;, and each method with &lt;strong&gt;@ExceptionHandler&lt;/strong&gt; annotation means that when that exception occurs that method will be responsible for the treatment and return.&lt;/p&gt;

&lt;p&gt;We are using a global Exception to deal with the global expection and ResourceNotFoundException for the situation mentioned before.&lt;/p&gt;
&lt;h2&gt;
  
  
  Use ResourceNotFoundException in ProductService
&lt;/h2&gt;

&lt;p&gt;Now let's improve the methods, first with the method &lt;strong&gt;findById&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public Product findById(Long id) {
        return repository.findById(id).orElseThrow(() -&amp;gt; new ResourceNotFoundException("Not found Product with this ID"));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When not found a product with the given ID, exception will be thrown.&lt;/p&gt;

&lt;p&gt;About the &lt;strong&gt;update&lt;/strong&gt; and &lt;strong&gt;delete&lt;/strong&gt;, only refractory to use &lt;strong&gt;findById&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @Transactional
    public Product update(Product product, Long id) {
        var productPersisted = findById(id);

        BeanUtils.copyProperties(product, productPersisted, "id");

        return repository.save(productPersisted);
    }

    @Transactional
    public void delete(Long id) {
        var productPersisted = findById(id);
        repository.delete(productPersisted);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Use ResponseEntity in ResponseEntity
&lt;/h2&gt;

&lt;p&gt;All methods need to return a ResponseEntity with the perfect code to that situation, so look the below change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;Product&amp;gt; create(@RequestBody ProductCreateUpdate productCreate) {
        Product product = new Product();
        BeanUtils.copyProperties(productCreate, product);

        return ResponseEntity.status(HttpStatus.CREATED).body(service.create(product));
    }

    @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;Product&amp;gt; findById(@PathVariable(value = "id") Long id) {
        return ResponseEntity.status(HttpStatus.OK).body(service.findById(id));
    }

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;List&amp;lt;Product&amp;gt;&amp;gt; findAll() {
        var products = service.findAll();
        if (products.isEmpty()) return ResponseEntity.noContent().build();
        return ResponseEntity.status(HttpStatus.OK).body(products);
    }

    @PutMapping(path = "/{id}",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&amp;lt;Product&amp;gt; update(@PathVariable(value = "id") Long id, @RequestBody ProductCreateUpdate productUpdate) {
        Product product = new Product();
        BeanUtils.copyProperties(productUpdate, product);

        return ResponseEntity.status(HttpStatus.OK).body(service.update(product, id));
    }

    @DeleteMapping(path = "/{id}")
    public ResponseEntity&amp;lt;?&amp;gt; delete(@PathVariable(value = "id") Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;strong&gt;ResponseEntity&lt;/strong&gt; is used to return a entity declare in &lt;strong&gt;&amp;lt;&amp;gt;&lt;/strong&gt;, to return a specific code, use the method &lt;strong&gt;.status()&lt;/strong&gt; with enum &lt;strong&gt;HttpStatus&lt;/strong&gt;, and a body use &lt;strong&gt;.body()&lt;/strong&gt;.&lt;br&gt;
The method &lt;strong&gt;create&lt;/strong&gt; will return a code &lt;strong&gt;CREATED&lt;/strong&gt; = 201 and a entity Product.&lt;br&gt;
The method &lt;strong&gt;findById&lt;/strong&gt; and &lt;strong&gt;update&lt;/strong&gt; return &lt;strong&gt;OK&lt;/strong&gt; = 200 with the product, but if not find a Product with that ID, the return is &lt;strong&gt;NOT_FOUND&lt;/strong&gt;.&lt;br&gt;
The method &lt;strong&gt;findAll&lt;/strong&gt; return &lt;strong&gt;OK&lt;/strong&gt; if exist some value, else return &lt;strong&gt;NO_CONTENT&lt;/strong&gt; = 204.&lt;br&gt;
The method &lt;strong&gt;delete&lt;/strong&gt; always return &lt;strong&gt;NO_CONTENT&lt;/strong&gt; because don't have a product, but like the findById and update when not find a product return &lt;strong&gt;NOT_FOUND&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing
&lt;/h2&gt;

&lt;p&gt;In Postman do this request to see the different codes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7zc4e1hha6k54bsnz638.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7zc4e1hha6k54bsnz638.png" alt="post" width="800" height="480"&gt;&lt;/a&gt;&lt;br&gt;
Now when the &lt;strong&gt;POST localhost:8080/api/product&lt;/strong&gt; is requested, the code return is &lt;strong&gt;201 Created&lt;/strong&gt;.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hgbr337dkoebckma3o7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hgbr337dkoebckma3o7.png" alt="get200" width="800" height="465"&gt;&lt;/a&gt;&lt;br&gt;
When the &lt;strong&gt;GET/PUT localhost:8080/api/product/1&lt;/strong&gt; is requested, the response code is &lt;strong&gt;200 OK&lt;/strong&gt;, but if put a ID that don't exist the return is &lt;strong&gt;404 NOT FOUND&lt;/strong&gt;.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa6vikd1svuf13ggg9u7a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa6vikd1svuf13ggg9u7a.png" alt="getnot found" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;The &lt;strong&gt;GET localhost:8080/api/product&lt;/strong&gt; now return &lt;strong&gt;200 OK&lt;/strong&gt; when find some product, but if doesn't exist anyone, return &lt;strong&gt;204 No Content&lt;/strong&gt;.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz0a7eylzcacklcxuzzuj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz0a7eylzcacklcxuzzuj.png" alt="findall" width="800" height="365"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;To finish the &lt;strong&gt;DELETE&lt;/strong&gt; in &lt;strong&gt;localhost:8080/api/product/&lt;/strong&gt;1 return &lt;strong&gt;204 No Content&lt;/strong&gt;.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzuk37k6suxq07q0dbzco.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzuk37k6suxq07q0dbzco.png" alt="delete" width="800" height="376"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Noticed that when a custom exception error ResourceNotFoundException is returned, a return comes as created in the record class ExceptionResponse.&lt;/p&gt;

&lt;p&gt;I don't do all possible return because they are like in class ProductController explanation, but feel free to test all.&lt;/p&gt;

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

&lt;p&gt;In this post, we create the global class with @ControllerAdvice annotation to deal with all expectations.&lt;br&gt;
Also improving the service and controller class to use ResponseEntity.&lt;/p&gt;

&lt;h2&gt;
  
  
  Next Step
&lt;/h2&gt;

&lt;p&gt;In the next step we will create validations in the body of the request received.&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>restapi</category>
      <category>spring</category>
    </item>
  </channel>
</rss>
