<?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 Miguel Angel Perez Diaz on Medium]]></title>
        <description><![CDATA[Stories by Miguel Angel Perez Diaz on Medium]]></description>
        <link>https://medium.com/@miguelangelperezdiaz444?source=rss-6020d06ec40c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1WGOaey-n4h4pG8eHKzdpA.png</url>
            <title>Stories by Miguel Angel Perez Diaz on Medium</title>
            <link>https://medium.com/@miguelangelperezdiaz444?source=rss-6020d06ec40c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:02:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miguelangelperezdiaz444/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[ Mastering Exception Handling in Spring : @RestControllerAdvice]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/mastering-exception-handling-in-spring-restcontrolleradvice-3bd85d473b0d?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd85d473b0d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[restcontrolleradvice]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 09:38:17 GMT</pubDate>
            <atom:updated>2023-10-22T09:38:17.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>🤿 Mastering Exception Handling in Spring : <strong>@RestControllerAdvice</strong></h3><figure><img alt="Exception Handling in Spring Diagram" src="https://cdn-images-1.medium.com/max/1024/1*27zfzN0V8YfJPdDvC4CtuQ.jpeg" /></figure><p><em>Exception handling, in the broader context of software development, refers to the systematic approach of managing and responding to unexpected events or errors that can occur during the execution of a computer program. These exceptions can range from runtime errors and network failures to input validation issues. The primary goal of exception handling is to </em><strong><em>prevent application crashes and provide a graceful response</em></strong><em> to users when errors occur, enhancing the reliability and resilience of the software.</em></p><p><em>In this guide, we will delve into the specific techniques and practices for implementing effective </em><strong><em>Exception Handling in Spring</em></strong><em>, with a particular emphasis on the versatile </em><strong><em>@RestControllerAdvice</em></strong><em> annotation.</em></p><p><em>We’ll explore best practices, practical examples, and key insights to empower your application’s resilience.</em></p><h3>📕 Fundamentals of Exception Handling in Java</h3><p>Before delving into advanced concepts, let’s establish a foundation in Java’s exception handling.<strong> The try-catch mechanism</strong> stands as the fundamental approach. Place your code within a try block, and any exceptions thrown by the code are intercepted by one or more catch blocks.</p><p>This method effectively captures various types of <strong>Java exceptions</strong>, making it a straightforward and essential approach for managing errors.</p><pre>try {<br>  // code which can throw exceptions<br>} catch (final Exception ex) {<br>  // Exception handling<br>  System.out.printf(&quot;Error with message: %s&quot;, ex.getMessage());<br>}</pre><p>Important Note: A tryblock cannot stand alone. It must be directly followed by either a catchor a finallyblock.”</p><h4>Targeted Exception Handling in Java</h4><p>In Java, you have the flexibility to capture specific exceptions, enabling you to craft dedicated code for handling particular errors. For instance, in the context of REST API errors, some are recoverable while others are not. This approach allows you to distinguish between these scenarios.</p><p>To achieve this, you can extend a tryblock with multiple catchblocks, each specifying a distinct exception type. When an exception occurs, Java executes the first catchblock that matches the exception class or one of its superclasses. Therefore, it’s important to prioritize the catchblocks with the most specific exception classes.</p><pre>try {<br>  // code which can throw exceptions<br>} catch (NumberException ex) {<br>  // exception handler for NumberException<br>  System.out.printf(&quot;Error with message: %s&quot;, ex.getMessage());<br>} catch (NumberFormatException ex) {<br>  // Exception handler for NumberFormatException<br>  System.out.printf(&quot;Error handling number format: %s&quot;, ex.getMessage());<br>  <br>}</pre><p>When an exception is triggered within the tryblock, it is directed to the initial catchblock. If the exception isn’t handled there, it proceeds to the subsequent catchstatement. This process repeats until the exception is either intercepted or exhausts all available catchblocks.</p><h4>The Importance of the finally Block</h4><p>A finally block is where you place code that <strong>must execute regardless of whether an exception occurs</strong>. In simple terms, the finally block guarantees execution under all circumstances. For instance, if you have an open connection to a database or file, the finally block is ideal for closing the connection, ensuring it happens even if the try block encounters a Java exception.</p><pre>try {<br>  // code which can throw exceptions<br>} catch (NumberException ex) {<br>  // exception handler for NumberException<br>  System.out.printf(&quot;Error with message: %s&quot;, ex.getMessage());<br>} catch (NumberFormatException ex) {<br>  // Exception handler for NumberFormatException<br>  System.out.printf(&quot;Error handling number format: %s&quot;, ex.getMessage());<br>  <br>} finally {<br>  // finally block always executes<br>}</pre><h3>🎓Introduction to @RestControllerAdvice</h3><p>The @RestControllerAdvice annotation is a specialized form of the @Componentannotation, which enables automatic detection through classpath scanning. <strong>It serves as an interceptor that envelops the operations within our Controllers, allowing us to apply common logic to them.</strong></p><p>The methods within @RestControllerAdvice (marked with @ExceptionHandler) are accessible globally to multiple @Controllercomponents, and their purpose is to catch exceptions and transform them into HTTP responses. The @ExceptionHandlerannotation specifies the type of Exception that should be managed. The method will receive the exception instance and the request as method arguments.</p><p>By combining these two annotations, we achieve the following:</p><ol><li>Control over the response content and status code.</li><li>The ability to handle multiple exceptions within a single method.</li></ol><h4>🤔 @RestControllerAdvice or @ControllerAdvice?</h4><p>In the Spring Framework’s landscape of exception handling, two key annotations, @RestControllerAdvice and @ControllerAdvice, play distinct roles. Understanding their differences is crucial for effective application development.</p><p><strong>@ControllerAdvice</strong>: This annotation is well-suited for applications that primarily generate traditional HTML views. When your application is focused on rendering web pages, @ControllerAdvice is the appropriate choice. It excels at handling exceptions within the context of web views and provides a means to customize <strong>error responses in HTML format</strong>.</p><p><strong>@RestControllerAdvice</strong>: In contrast, @RestControllerAdvice finds its niche in applications that predominantly serve <strong>data in JSON, XML</strong>, or other structured formats. This is especially common in <strong>RESTful web services</strong>, where the primary task is delivering data to clients. @RestControllerAdviceis designed to manage exceptions and tailor error responses specifically for these data-centric scenarios.</p><p>However, @ControllerAdvicecan also be used for REST services, but the following must be taken into account:</p><ul><li>@RestControllerAdvice is a composed annotation that is annotated with both <strong>@ControllerAdvice and </strong><strong>@ResponseBody</strong>, which essentially means @ExceptionHandler methods are rendered to the response body through message conversion (versus view resolution or template rendering), so @ControllerAdvice can be used even for REST web services as well, but you need to additionally use @ResponseBody.</li></ul><p><a href="https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-advice.html">Controller Advice</a></p><h3>✨Advantages of Using @RestControllerAdvice</h3><p>Discover the benefits of @RestControllerAdvice and its role in Exception Handling in Spring for data-centric applications:</p><p><strong>1. Streamlined Error Responses: </strong>@RestControllerAdvice empowers developers to craft consistent and structured error responses in formats like JSON or XML. This standardization enhances communication between the application and its clients, making it easier to interpret and handle errors programmatically.</p><p><strong>2. Precision in RESTful Environments: </strong>RESTful services often require pinpoint precision in “exception handling in Spring.” With @RestControllerAdvice, you can tailor error messages to meet the specific needs of your RESTful API clients, ensuring that they receive informative and contextually relevant responses.</p><p><strong>3. Enhanced Data Validation</strong>: Data validation is paramount in RESTful services. @RestControllerAdvice makes it simpler to validate incoming data and promptly respond with clear validation error messages, helping to maintain data integrity and reduce the risk of erroneous data entry.</p><p><strong>4. Simplified Exception Handling: </strong>Exception handling becomes more straightforward with @RestControllerAdvice. By consolidating error-handling logic in one place, it simplifies code maintenance and reduces redundancy, resulting in cleaner and more maintainable codebases.</p><p><strong>5. Focused Approach:</strong> @RestControllerAdvice is well-suited to applications where the primary focus is delivering data. This specialization allows developers to address exceptions and errors in a way that&#39;s tailored to the data-driven nature of their applications.</p><p>These advantages underscore the importance of @RestControllerAdvice in the context of RESTful services and data-centric applications. By leveraging its capabilities, developers can ensure that their applications not only handle errors gracefully but also provide a seamless and reliable experience to their users and clients.</p><p>In the subsequent sections, we’ll explore practical examples and delve deeper into best practices for harnessing the full potential of @RestControllerAdvice in your Spring-based projects.</p><h3>💣Practical Implementation:</h3><p>To test the functionality of @RestControllerAdvice and its different use cases, we are going to define two small use cases where we will create a new client and search for it using its identifier. To do this I bring you a custom error handling approach that I personally find to be a pretty clean and robust solution:</p><h4>Starting Point:</h4><pre>@RestController<br>@RequiredArgsConstructor<br>public class ClientController {<br><br>    private final ClientService clientService;<br><br>    @PostMapping(&quot;api/v1/clients&quot;)<br>    public ClientDTO create(@RequestBody ClientDTO clientDTO) {<br>        try {<br>            return this.clientService.create(clientDTO);<br>        } catch (ClientAlreadyExistsException ex) {<br>            System.out.println(&quot;Client already exists&quot;);<br>            throw new CustomException1(ex.getMessage());<br><br>        } catch (EmailBadFormatException ex) {<br>            System.out.println(&quot;Email has bad format&quot;);<br>            throw new CustomException2(ex.getMessage());<br>        }<br>    }<br><br>    @GetMapping(&quot;api/v1/clients/{id}&quot;)<br>    public ClientDTO find(@PathVariable Long id) {<br>        try {<br>            return this.clientService.find(id);<br>        } catch (ClientNotFoundException ex) {<br>            System.out.println(&quot;Client already exists&quot;);<br>            throw new CustomException3(ex.getMessage());<br><br>        }<br>    }<br>}</pre><p>As you can see, this is a very basic example of exception handling, but you can see how the complexity of the controller grows as the number of conditions in our application grows, so the readability of our code is affected.</p><p>To improve this we are going to create our @RestControllerAdvice that will be our central point of handling exceptions, cleaning this way the rest of the application of this arduous task.</p><p>Initially we are going to define our “abstract” exception that <strong>must inherit from </strong><strong>RuntimeException</strong>and where we are going to define the fields that we want to collect in our exceptions. This class will be the parent of the rest of exceptions that we define in our application:</p><pre>@Getter<br>@Setter<br>@AllArgsConstructor<br>public class AbstractException extends RuntimeException {<br><br>    private String message;<br><br>    private Map&lt;String, String&gt; details;<br><br>}</pre><p>In our case we only want to collect a custom message and a detail map where we can give more detailed information of the exception that has occurred (the definition of the fields is on demand, needs of the application or imagination of each developer).</p><p>Next we are going to create 2 custom exceptions: one for the calls to our API Rest invalid and another one for when a certain entity is found inside the application.</p><pre>public class EntityNotFoundException extends AbstractException {<br>    <br>    public EntityNotFoundException(String message, Map&lt;String, String&gt; details) {<br>        super(message, details);<br>    }<br>}</pre><pre>public class InvalidCallException extends AbstractException {<br><br>    public InvalidCallException(String message, Map&lt;String, String&gt; details) {<br>        super(message, details);<br>    }<br>}</pre><p>As you can see, they simply call the constructor of theAbstractException that we have created previously. At this point, this is customizable, for example we could also define a static message for each type of exceptions and that inside detailswe have more concrete information of our exception.</p><p>Finally we define our global exception handler together with the error DTO that we want to send to the client (frontend) to be painted on the screen or handle it in the way it deems most appropriate :</p><pre>@Data<br>@Builder<br>public class ErrorMessageDTO implements Serializable {<br><br><br>    private String message;<br><br>    private Instant date;<br><br>    private Map&lt;String, String&gt; details;<br><br>}</pre><pre>@RestControllerAdvice<br>public class GlobalExceptionResponseHandler {<br>    <br>    @ExceptionHandler(value = {InvalidCallException.class})<br>    @ResponseStatus(HttpStatus.BAD_REQUEST)<br>    public ErrorMessageDTO mapInvalidCallException(InvalidCallException ex, WebRequest request) {<br><br>        return ErrorMessageDTO.builder()<br>                .message(ex.getMessage())<br>                .date(Instant.now())<br>                .details(ex.getDetails())<br>                .build();<br>    }<br><br>    @ExceptionHandler(value = {EntityNotFoundException.class})<br>    @ResponseStatus(HttpStatus.NOT_FOUND)<br>    public ErrorMessageDTO mapNotFoundException(EntityNotFoundException ex, WebRequest request) {<br><br>        return ErrorMessageDTO.builder()<br>                .message(ex.getMessage())<br>                .date(Instant.now())<br>                .details(ex.getDetails())<br>                .build();<br>    }<br><br><br><br>}</pre><p>The operation of our global exception handler is quite simple, we simply annotate the class with @RestControllerAdviceand define a method for each type of exception depending on the HTTP Status we want to send to the client. <br><strong>In each method, we need to define in </strong><strong>@ExceptionHandler the exception to be handled in that method + </strong><strong>@ResponseStatus indicating the HTTP status to be sent to the client.</strong></p><p>At this point, each method handles the exception that is indicated and is built in response DTO based on the fields of our AbstractException (it is the parent exception that defines the fields used by InvalidadCallException and EntityNotFoundException).</p><p>All this architecture is customizable, for example we could also define an ExceptionMessagesEnum where we define the messages that we want to send to the client and then reuse this enum when sending exceptions of the type that we consider. For example :</p><pre>@Getter<br>@AllArgsConstructor<br>public enum ExceptionMessagesEnum {<br>    <br>    CLIENT_NOT_FOUND(&quot;Client not found&quot;),<br>    <br>    EMAIL_BAD_FORMAT(&quot;Email has bad format&quot;),<br>    <br>    CLIENT_ALREADY_EXISTS(&quot;Client already exists&quot;);<br>    <br>    private final String description;<br><br>}</pre><p>In our service :</p><pre>public ClientDTO find(Long id) {<br>    return this.clientRepository.findById(id)<br>            .map(this.mapper::asDto)<br>            .orElseThrow(() -&gt; new EntityNotFoundException(CLIENT_NOT_FOUND.getDescription(), Map.of(&quot;ID&quot;, String.valueOf(id))));<br><br><br>}</pre><p><strong>Results 🎉:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*G9f7-oX9q2jjUq2iQcpExw.png" /></figure><blockquote>We can even add an improvement: if our application has Internationalization, we can redefine our exception enum descriptionfield to indicate the key of our messages.propertiesfiles. So that in our global exception handler we inject the MessageSourcebean to obtain the internationalized message based on this new field.</blockquote><blockquote><a href="https://www.baeldung.com/spring-boot-internationalization">https://www.baeldung.com/spring-boot-internationalization</a></blockquote><h3>🥇Best Practices</h3><p>In the realm of “Exception Handling in Spring,” following best practices is paramount to ensure the resilience and reliability of your applications. Here are some key recommendations to consider:</p><ul><li><strong>Precise Exception Selection</strong>: Exception handling begins with the selection of the right exception type. Choose exceptions that accurately reflect the error scenario to provide meaningful responses.</li><li><strong>Custom Error Messages</strong>: Tailor error messages to convey relevant information to users and developers. Include error codes, descriptions, and guidance for resolution.</li><li><strong>Logging and Monitoring:</strong> Implement robust logging to capture error details. Additionally, set up monitoring to proactively identify and address recurring issues.</li><li><strong>Global Exception Handling:</strong> Consider using a global exception handler to centralize common exception handling logic. This enhances code maintainability and reduces redundancy.</li><li><strong>Testing and Validation:</strong> Rigorously test your exception handling logic to ensure it functions as intended. Validate data inputs to preemptively catch errors.</li><li><strong>Documentation: </strong>Document your exception handling strategies and the responses provided. This documentation serves as a valuable resource for your development team and API consumers.</li><li><strong>Regular Updates:</strong> Review and update your exception handling mechanisms as your application evolves. Ensure they remain aligned with your application’s evolving requirements.</li><li><strong>Security Considerations:</strong> When handling exceptions, be mindful of potential security vulnerabilities. Avoid exposing sensitive information in error messages.</li></ul><p>By adhering to these best practices, you can create a robust and reliable Exception Handling in Spring that not only enhances user experience but also streamlines development and troubleshooting efforts.</p><h3>🏁 Conclusions and Additional Resources</h3><p>In conclusion, this guide has provided a comprehensive understanding of Exception Handling in Spring with a particular focus on the versatile @RestControllerAdvice annotation. We&#39;ve explored the fundamentals of Exception Handling in Spring, highlighting the critical role it plays in building robust and reliable applications.</p><p>As you embark on your journey to enhance your application’s resilience, remember to follow best practices, customize error messages, and maintain precision in error responses. Continuously update and test your exception handling mechanisms to align with evolving application requirements.</p><p>To further expand your knowledge and proficiency in Spring Framework and Exception Handling, consider exploring the following additional resources:</p><ol><li><em>Spring Framework Documentation</em>: The official Spring Framework documentation offers in-depth insights, tutorials, and reference materials to help you master Spring’s various components and features.</li><li><em>Online Communities</em>: Engage with online communities, forums, and discussion boards related to Spring Framework. Platforms like Stack Overflow and the Spring Community Forum provide a space for developers to seek help and share knowledge.</li><li><em>Advanced Spring Courses</em>: Consider enrolling in advanced Spring courses or certifications to deepen your expertise in Spring Framework and its advanced features.</li><li><em>Books:</em> Explore books dedicated to Spring Framework and Exception Handling to gain in-depth knowledge and practical insights from experienced authors.</li></ol><p>By continuing to learn and apply best practices, you’ll be well-equipped to handle exceptions effectively and build resilient applications in the dynamic world of Spring Framework. <strong>Exception Handling in Spring</strong> is a critical aspect of application development, and your expertise in this area will set the foundation for reliable and user-friendly software.</p><h4>HAPPY CODING! 🎯</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd85d473b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring SSE (Server-Sent Events): Real-Time Updates for Your Applications!]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/exploring-sse-server-sent-events-real-time-updates-for-your-applications-5264a461ce6f?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5264a461ce6f</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 07:04:54 GMT</pubDate>
            <atom:updated>2024-02-03T11:55:59.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8qogIEC6hKUIuDtES6XeA.jpeg" /></figure><p><em>Real-time communication has become a critical aspect of modern web applications, enabling developers to deliver dynamic updates and interactive experiences to users. One powerful technology that facilitates real-time communication is Server-Sent Events (SSE). It has gained popularity due to its simplicity, ease of use, and compatibility with a wide range of web browsers and platforms.</em></p><p><em>In this blog post, we will delve into the world of SSE and its integration with the Spring Framework. We will explore how SSE can enhance the communication capabilities of Spring applications, enabling the delivery of real-time updates to clients. By harnessing the power of SSE in Spring, developers can create responsive and interactive web applications that keep users engaged and informed.</em></p><p><em>Join us as we unravel the potential of SSE in Spring and discover how this technology can transform your application’s real-time communication capabilities. Let’s dive into the exciting world of SSE and witness its impact on Spring-powered applications. 🚀</em></p><h3>📕 What is SSE (Server-Sent Events) ?</h3><p><strong>Server-Sent Events (SSE) is a web technology that enables servers to send real-time updates or events to clients over a single, long-lived HTTP connection</strong>. It is a <strong>simple and efficient alternative</strong> to other real-time communication protocols like <strong>WebSocket.</strong></p><p>Unlike traditional HTTP requests where the client initiates the communication, <strong>SSE allows the server to initiate the communication and push data to the client whenever new events or updates occur</strong>. This push-based model eliminates the need for the client to repeatedly poll the server for updates, resulting in reduced network overhead and improved efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*fZqr0oanvckFPpwm.png" /></figure><p>SSE relies on the EventSource API on the client side, which provides a convenient way to handle incoming events. The server sends data to the client in a specific format called “text/event-stream.” Each event consists of a data field containing the payload and optional event and ID fields.</p><p><strong>SSE is supported by most modern web browsers and can be easily integrated into web applications built on various platforms and frameworks</strong>. In the context of the Spring Framework, SSE can be seamlessly integrated to enable real-time communication and push updates to clients, making it an excellent choice for applications that require real-time data synchronization, notifications, or live feeds.</p><h4>🚩 SSE limitations :</h4><p>While Server-Sent Events (SSE) offers an efficient and straightforward approach to real-time communication, it does have some limitations to consider:</p><ul><li><strong>Unidirectional Communication</strong>: SSE supports server-to-client communication only. Clients cannot send data or interact with the server through the SSE connection. If bidirectional communication is required, alternative technologies like WebSocket should be considered.</li><li><strong>Lack of Binary Data Support</strong>: SSE is primarily designed for sending textual data. It does not natively support the transmission of binary data. If you need to transfer binary information, you would need to encode it into a textual format (e.g., Base64) before sending it over SSE.</li><li><strong>Limited Browser Support</strong>: While most modern web browsers support SSE, there may still be some older browsers or niche platforms that do not have SSE capabilities. It’s essential to consider the target audience and browser compatibility requirements when deciding to use SSE.</li><li><strong>Connection Limitations</strong>: SSE suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is <em>per browser</em> and is set to a very low number (6). This limit is per browser + domain, which means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com.When using HTTP/2, the maximum number of simultaneous <em>HTTP streams</em> is negotiated between the server and the client (defaults to 100).</li></ul><h3>🍃 Integration with Spring MVC— Spring Boot</h3><ul><li><strong>Configure Dependencies</strong>: Include the required dependencies in your project. For SSE support, you’ll need the spring-web module, which is typically part of the Spring Web MVC framework.</li></ul><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><ul><li><strong>Create an SSE Controller:</strong> In Spring, you can create a controller dedicated to handling SSE requests. Annotate the controller class with @RestController or @Controller and the appropriate request mapping annotations (@RequestMapping, @GetMapping, etc.).</li><li><strong>Implement SSE Endpoint</strong>: Within the SSE controller, define a method that will serve as the SSE endpoint. Annotate this method with @GetMapping or the corresponding mapping annotation, and return a SseEmitter object from the method.</li></ul><pre>@Slf4j<br>@RestController<br>@RequiredArgsConstructor<br>@RequestMapping(&quot;/api/v1/sse&quot;)<br>public class SseController {<br><br>  private final SseService sseService;<br><br>  @GetMapping(value = &quot;/stream&quot;, produces = MediaType.TEXT_EVENT_STREAM_VALUE)<br>  public SseEmitter subscribeToSseEvents() {<br>    return this.sseService.subscribe();<br>  }<br><br>}</pre><ul><li><strong>Store the emitter</strong> to later send the different events generated by the application at the points in the code where it is necessary.</li></ul><pre>private final CopyOnWriteArrayList&lt;SseEmitter&gt; emitters = new CopyOnWriteArrayList&lt;&gt;();<br><br>public SseEmitter subscribe() {<br>  final SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);<br>  this.emitters.add(emitter);<br><br>  emitter.onCompletion(() -&gt; this.emitters.remove(emitter));<br><br>  return emitter;<br>}</pre><p>The value specified in the constructor of the SseEmitter class is the timeout in milliseconds, normally it has a default value quite short, in the example we have set the value Long.MAX_VALUE to set a maximum time to have time left over, but it is a value that you can adapt depending on the needs of your application. 🚩</p><p>The documentation indicates : <em>By default not set in which case the default configured in the MVC Java Config or the MVC namespace is used, or if that’s not set, then the timeout depends on the default of the underlying server.</em></p><ul><li><strong>Finally, we only need to trigger the event</strong> in the use cases where we want to send information to the client. For this I have defined a method in our SseService :</li></ul><pre>public void sendEvent(final String message) {<br><br>  this.emitters.forEach(emitter -&gt; {<br>    try {<br>      emitter.send(SseEmitter.event()<br>          .name(&quot;event-test&quot;)<br>          .data(SseMessage.builder()<br>              .description(message)<br>              .build()));<br>    } catch (final Exception e) {<br>      emitter.complete();<br>    }<br>  });</pre><p>Here we simply scroll through the list of previously stored subscribers and send the corresponding event. The “name” field of the event indicates the name of the event (we can customise this so that we can capture it in a personalised way in the client, otherwise the default value is “message”), the “data” field is the body of the event, here we can send a Java Object, so we can send the information that is relevant in each case. (in my case, I only send plain text, a string).</p><blockquote><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.html">https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.html</a></blockquote><h3>🎨 Integration with JavasScript</h3><p>To integrate Server-Sent Events (SSE) with JavaScript, you can follow these steps:</p><ol><li><strong>Create an EventSource Object</strong>: Instantiate a new EventSource object in your JavaScript code by providing the SSE endpoint URL as a parameter. For example:</li></ol><pre>const eventSource = new EventSource(&#39;http://localhost:8080/api/v1/sse/stream&#39;);</pre><p>2. <strong>Register Event Listeners</strong>: Attach event listeners to handle different types of SSE events. The EventSource object supports three main events: open, message, and error. For instance:</p><pre>eventSource.addEventListener(&#39;open&#39;, () =&gt; {<br>  // Connection is established<br>});<br><br>eventSource.addEventListener(&#39;event-test&#39;, (event) =&gt; {<br>  // Handle SSE event data<br>  const eventData = JSON.parse(event.data);<br>  console.log(eventData);<br>  // Process and use the received data<br>});<br><br>eventSource.addEventListener(&#39;error&#39;, () =&gt; {<br>  // Handle SSE connection errors<br>});</pre><p>3. <strong>Receive SSE Events:</strong> When the server sends SSE events, the event-testevent listener will be triggered (it is the event name that I indicate in Spring Integration, but it is ‘message’ by default) . Access the event data using event.data and perform the desired actions with the received data. You can update the UI, trigger specific functions, or process the data in any way you need.</p><p>4. <strong>Close the Connection</strong>: When you’re done with SSE, make sure to close the connection to free up resources. You can use the close() method of the EventSource object to close the SSE connection:</p><pre>eventSource.close();</pre><p>By following these steps, you can integrate SSE with JavaScript and receive real-time updates from the server. Remember to handle any necessary error cases, clean up the SSE connection when it’s no longer needed, and ensure that the SSE endpoint on the server-side is correctly configured to send SSE events to connected clients.</p><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">https://developer.mozilla.org/en-US/docs/Web/API/EventSource</a></blockquote><h3>🏁 Conclusion</h3><p>Server-Sent Events (SSE) provide a straightforward and efficient approach to real-time communication between servers and clients. With SSE, the server can push data updates to clients over a single, long-lived HTTP connection, eliminating the need for constant polling.</p><p>Integrating SSE with Spring allows developers to enhance the real-time communication capabilities of their applications. By configuring SSE endpoints, emitting SSE events, and leveraging the EventSource API on the client-side, developers can enable seamless real-time updates, notifications, and data synchronization.</p><p>When using SSE with JavaScript, such as in a React application, creating an EventSource object, registering event listeners, and handling SSE events becomes straightforward. The received SSE data can then be processed and utilized within the application to update the user interface or trigger specific actions.</p><p>While SSE has some limitations, such as unidirectional communication and limited browser support, it remains a powerful tool for delivering real-time updates in a simple and compatible manner.</p><p>By harnessing the capabilities of SSE in conjunction with frameworks like Spring and JavaScript libraries like React, developers can build interactive and responsive applications that deliver real-time experiences to their users.</p><h4>HAPPY CODING! 🎯</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5264a461ce6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Boost Your Productivity: Tips and Tricks for IntelliJ IDE!]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/boost-your-productivity-tips-and-tricks-for-intellij-ide-5ae75a323e21?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae75a323e21</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 17:23:31 GMT</pubDate>
            <atom:updated>2023-06-14T17:23:31.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxI82hKe_P2voaSdW6znCA.jpeg" /></figure><p>Welcome to our blog post, where we dive into the world of IntelliJ IDE and unveil a treasure trove of tips and tricks to supercharge your productivity. Whether you’re a seasoned IntelliJ user or just getting started, this article is here to help you harness the full potential of this powerful integrated development environment.</p><p>IntelliJ IDEA, developed by JetBrains, is renowned for its robust features and intelligent code analysis capabilities. However, there are numerous hidden gems and lesser-known features that can significantly enhance your coding experience and save you valuable time. In this post, we’ll explore a curated collection of tips and tricks, ranging from keyboard shortcuts and navigation techniques to code refactoring and advanced debugging techniques.</p><p>By the end of this read, you’ll be equipped with a toolkit of IntelliJ wizardry, enabling you to streamline your workflow, discover new shortcuts, and leverage powerful features that may have remained undiscovered until now. So, let’s dive in and unlock the secrets of IntelliJ, empowering you to become a more efficient and proficient developer.</p><h3>🐛Debug Mode</h3><p>Regarding the debugging part of the code, we can comment on the great variety of options that IntelliJ offers us as an IDE to find and solve errors/bugs in our code, but today we are going to talk about certain options/functionalities that, at least when I was a junior developer, I didn’t know and nobody taught me and that I think can help a lot in debugging tasks to any developer regardless of the level he/she has.</p><p><strong>❓ Conditional Breakpoints : </strong>Most developers are familiar with breakpoints when debugging, but what if you have to debug a loop with several iterations? do you skip each iteration until you get to the object you really want to debug? Well, IntelliJ offers us conditional breakpoints that work practically in the same way as the previous ones but we can <strong>indicate a condition in which the breakpoint will be activated</strong>, which will save us from being aware of the different iterations of the previous loop and focus only on the object we want to observe.</p><p><strong>To make use of it, simply put a breakpoint where you want it and then right click on it and you will get the input to indicate the condition in which you want the breakpoint to be activated</strong>. For example :</p><pre>public List&lt;User&gt; addAddress(Address address) {<br><br>    List&lt;User&gt; users = userRepository.findAll();<br><br>    for (User user : users) {<br>      user.addAddress(address);<br>    }<br><br>    return users;<br><br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*xAKGiceOTETJTv85DhpApQ.png" /></figure><p><strong>🤿 Streams : </strong>Streams are one of the best features that Java 8 brought us, but it is true that they can be difficult to debug and even more so if we nest Stream operations such as filter, map or flatMap. That’s why IntelliJ offers us a tool to debug streams and see the result that each Stream operation gives us until we get the final result.</p><p><strong>To be able to do this, it is quite simple, just put a breakpoint where our stream starts and we will see how one of the options that IntelliJ offers to debug is activated</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLJ1k3vkFu8RxYOAIz8XYg.png" /></figure><p>If we click on the debug option, we will see the result of each Stream operation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*-Q5zpvsaYNi2kYnz-U2vJQ.png" /></figure><p>Or if you want to see each step independently you can select the Split Modeoption at the bottom left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*vUTx20CovndkmLbT2g7MEQ.png" /></figure><p><strong>🔋 Recompile a file in execution time : </strong>Many times it happens that we start our application in debug mode and while debugging we notice an error/bug in our code and we all know that to test again once the error is corrected, we have to restart the application with all the time it may take … or not? IntelliJ offers us an option to<strong> recompile our file that we have just corrected at runtime and so we can test again the flow without having to restart the application.</strong></p><p><strong>Simply right click on the file we have corrected and select the option: </strong><strong>Compile and Reload File.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*1poWc7RmvM3PGNyKIUxjUw.png" /></figure><h3>🎩 Shortcuts</h3><p>In this section we are going to comment a little bit the different functionalities that IntelliJ offers us in terms of shortcuts. This part is not going to be the typical of most blogs that write the shortcuts that you can find in the IntelliJ web and that many of them are complicated or not used. I am not going to be very extensive in this part but I am going to comment some concepts that I believe that can help the developer to improve his productivity.</p><p><strong>🔙 Turn back : </strong>Has it ever happened to you that you are in a file and you go into one method and then into another and then you can’t find the initial file or you have to look for it again in the explorer? Well, there is a back option that <strong>allows you to switch back to the file you have previously opened</strong>. This functionality, I personally use it a lot in the context discussed above, you go into the different methods of a particular flow and finally you find it difficult to return to the starting point, but with this button or shortcut (you can put it both ways) you save all that time.</p><p>Normally these buttons appear when you activate the toolbar in the view tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*5hks__OG06k3kuZgMxZ9KA.png" /></figure><p>And they would look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*0xY0ckGEqjawdhOomDee8w.png" /></figure><p>Its corresponding shortcut would be :</p><ul><li><strong>CTRL + ALT + LEFT ARROW</strong></li><li><strong>CTRL + ALT + RIGHT ARROW</strong></li></ul><p><strong>📖 Live templates : </strong>IntelliJ IDEA has a feature called “Live Templates” that allows you to quickly <strong>insert predefined code snippets using keyboard shortcuts</strong>. For example, you can type “sout” and press the Tab key to automatically expand it into a System.out.println() code block. You can customize and create your own live templates in the IntelliJ IDEA configuration.</p><p>In this section plays an important role the imagination and performance of each one in the project you are in, since each one will have certain lines of code that repeats frequently and that can save time if you want a shortcut associated with that piece of code.</p><p><strong>To create a live template just go to Settings and enter “live template” in the search engine and an option should appear in the “Editor” section.</strong></p><p>As you can see, IntelliJ already has several predefined sections depending on the programming language we are using, but we can also create our own section with the “+” symbol that appears on the right side of the window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*jhdXeaAGYlYHD1pfXM3Wtw.png" /></figure><p>In my case I have selected java and clicked on the add button (“+”) to add a new live template to this group, and then a new window will open asking us for the abbreviation of our shortcut, a description if we wish and the part of the code that corresponds to our new shortcut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OvNGtqXYG0f1nGz3Olefw.png" /></figure><p>In this example we have created a <strong>Live Template</strong> to declare a logger in the class we want and in this way import it by simply typing in our code “log” and pressing the enter key to set it. As you can see, we have indicated the abbreviation with which we will call this shortcut <em>(“log”)</em>, a brief description and then in <em>“Edit variables”</em> we have given value to the variable declared in the expression $CLASS_NAME$ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*0LGqd6lBFtFCCzJIvFKHZQ.png" /></figure><p>In conclusion, this post explored the power of IntelliJ IDEA and its various features that enhance productivity and streamline the development process. We delved into the concept of Live Templates, which allow developers to save time by automating the insertion of frequently used code snippets. By creating custom Live Templates, developers can personalize their coding experience and reduce the need for repetitive typing.</p><p>Furthermore, we discussed the debugging capabilities of IntelliJ IDEA, particularly focusing on the debugging of Java 8 streams. The ability to set conditional breakpoints within streams enables developers to efficiently pinpoint and resolve issues in complex stream operations, saving valuable debugging time.</p><p>Additionally, we explored the convenient option of recompiling a single file in IntelliJ IDEA. This feature eliminates the need to rebuild the entire project, allowing for faster development iterations and reducing turnaround time.</p><p>IntelliJ IDEA’s array of features, including Live Templates, advanced debugging tools, and selective recompilation, empowers developers to write code more efficiently and effectively. By harnessing these features, developers can enhance their productivity, reduce time spent on repetitive tasks, and identify and fix bugs with ease.</p><p>Whether it’s through the automated code insertion of Live Templates, the streamlined debugging process, or the selective recompilation option, IntelliJ IDEA provides developers with the necessary tools to optimize their workflow and produce high-quality code.</p><p><strong>I hope this post will introduce you to new utilities to improve your productivity with IntelliJ!</strong></p><h4>Happy Coding! 🎯</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae75a323e21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Comparing Java Mapping Frameworks: A Performance Analysis!]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/comparing-java-mapping-frameworks-a-performance-analysis-f36d68c729e3?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36d68c729e3</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[mapping]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Sun, 21 May 2023 17:14:54 GMT</pubDate>
            <atom:updated>2023-05-21T17:14:54.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>📋 Java Object Mapping Frameworks: A Comprehensive Guide!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGs7CQ5WPGlh4B4c2jhq-A.png" /></figure><p>Java object mapping is an essential task when working with data-driven applications, as it allows us to convert between different data structures and simplify data access and manipulation. To help Java developers deal with mapping challenges, several Java mapping frameworks have been developed over the years. Each of these frameworks has its own strengths and weaknesses, making it challenging for developers to choose the right one for their use case.</p><p>In this article, we’ll take an in-depth look at four popular Java mapping frameworks: MapStruct, ModelMapper andJMapper. We’ll explore the use of each framework, as well as provide code examples to help you understand how to use them in practice.</p><p>By the end of this article, you’ll have a solid understanding of each of these Java mapping frameworks and be equipped to choose the best one for your project’s specific needs.</p><h3>🚩 Starting Point</h3><p><strong>In Java applications, it’s common to work with different data structures for different purposes. </strong>For example, you might have an object model that represents the entities in your domain, such as customers, orders, or products. At the same time, you might need to interact with a different set of data structures, such as data transfer objects (DTOs), for transferring data across different layers of your application or to external systems.</p><p>The need to convert between different data structures, such as domain objects and DTOs, led to the development of Java mapping frameworks. These frameworks automate the process of mapping one object to another, saving developers time and reducing the likelihood of errors.</p><p><strong>A DTO, or Data Transfer Object, is a Java object that is used to encapsulate data and transfer it between different layers or systems.</strong> DTOs typically contain a subset of the fields of a domain object, and they are designed to be lightweight and efficient for transfer over the network or between different parts of an application. By using DTOs, developers can separate the concerns of the domain model from those of the data transfer, making their code more modular and easier to maintain.</p><p>For our case we will define the domain entity User:</p><pre>public class User{<br>    private Long id;<br>    private String name;<br>    private String surname;<br>    private String email;<br>    private LocalDate creationDate;<br>    private List&lt;String&gt; addresses;<br>    private String role;<br><br>    // Getters y setters<br>}</pre><p>And its corresponding DTO :</p><pre>public class UserDto {<br>    private String name;<br>    private String surname;<br>    private String email;<br>    private List&lt;String&gt; addresses;<br><br>    // Getters y setters<br>}</pre><p>These will be the classes with which we will work and test the different mapping frameworks discussed.</p><h3>📕 MapStruct</h3><p>To start working with <strong>MapStruct</strong> we need to add the maven dependency to our project’s pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;<br>    &lt;artifactId&gt;mapstruct&lt;/artifactId&gt;<br>    &lt;version&gt;1.5.3.Final&lt;/version&gt; <br>&lt;/dependency&gt;</pre><p>Let’s also add the annotationProcessorPathssection to the configuration part of the maven-compiler-plugin plugin.</p><p>The mapstruct-processor is used to generate the mapper implementation during the build:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.5.1&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;source&gt;1.8&lt;/source&gt;<br>        &lt;target&gt;1.8&lt;/target&gt;<br>        &lt;annotationProcessorPaths&gt;<br>            &lt;path&gt;<br>                &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;<br>                &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;<br>                &lt;version&gt;1.5.3.Final&lt;/version&gt;<br>            &lt;/path&gt;<br>        &lt;/annotationProcessorPaths&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>Once we have all this, we can define our mapper. To do this we just need to define an interface which we will call UserMapperand we will mark it with the <strong><em>@Mapper</em></strong> annotation</p><p><strong>(<em>🚩 </em>if we want to inject it as a </strong><strong>Beanin any other Spring component, it is necessary to add the parameter </strong><strong>componentModel = with value : </strong><strong>&quot;spring”)</strong>:</p><pre>@Mapper(componentModel = &quot;spring&quot;)<br>public interface UserMapper {<br><br>  UserDto toDto(User user);<br><br>  User toEntity(UserDto dto);<br><br>}</pre><p>In this case, as the field names of the DTO and the entity match, there is no need to add anything else to our mapper.</p><p>B<strong>ut in the case that some of the fields do not match</strong>, for example in the DTO the name is defined in Spanish as “nombre”, then we would have to add above our mapping method the annotation <strong><em>@Mapping</em></strong>, indicating the name of the origin and destination field, like this :</p><pre>  @Mapping(target = &quot;nombre&quot;, source = &quot;name&quot;)<br>  UserDto toDto(User user);</pre><p>We are now ready to use our mapper, for example in our service. In our service we are going to inject it with the annotation <strong>@Autowired</strong> and just call the corresponding method that we have defined in the interface, for example :</p><pre>@Service<br>public class UserService {<br><br>  @Autowired<br>  private UserRepository userRepository;<br><br>  @Autowired<br>  private UserMapper userMapper;<br><br>  @Transactional(readOnly = true)<br>  public UserDto getUser(Long id) {<br>    return userMapper.toDto(userRepository.findById(id).orElseThrow(() -&gt; new EntityNotFoundException(&quot;User not found&quot;)));<br>  }<br><br>}</pre><h3>📘 ModelMapper</h3><p>To start working with <strong>ModelMapper </strong>we need to add the maven dependency to our project’s pom.xml:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.modelmapper&lt;/groupId&gt;<br>    &lt;artifactId&gt;modelmapper&lt;/artifactId&gt;<br>    &lt;version&gt;2.4.5&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Unlike the previous one, <strong>ModelMapper</strong> does not need more configuration aspects, simply by defining the dependency in our <em>pom.xml</em> file of the Maven project we have everything we need to be able to work with this tool.</p><p>In our case, as we want to inject into our service as a Bean, we will have to define it in a configuration class like this:</p><pre>@Configuration<br>public class Mapper {<br><br>  @Bean<br>  public ModelMapper modelMapper() {<br>    return new ModelMapper();<br>  }<br>  <br>}</pre><p>Once this is done, we can inject it with the <strong><em>@Autowired</em></strong> annotation. To use it, we will simply use the mapmethod offered by <strong>ModelMapper</strong> to which we will pass as first argument the object we want to convert and as second argument the class to convert the object to. So this would be an example of its use:</p><pre>@Service<br>public class UserService {<br><br>  @Autowired<br>  private UserRepository userRepository;<br><br>  @Autowired<br>  private ModelMapper mapper;<br><br>  @Transactional(readOnly = true)<br>  public UserDto getUser(Long id) {<br>    return mapper.map(userRepository.findById(id).orElseThrow(() -&gt; new EntityNotFoundException(&quot;User doesnt exist&quot;)), UserDto.class);<br>  }<br><br>}</pre><p>If for example we want to customise the mapping of a field like the example of the “name” field mentioned above, it is necessary to obtain the typeMap in charge of the mapping between both objects and add this rule to the mapper we have defined:</p><pre>mapper.getTypeMap(User.class,UserDto.class).addMapping(User::getName,UserDto::setNombre);</pre><h3>📗 JMapper</h3><p>To start working with <strong>JMapper </strong>we need to add the maven dependency to our <em>project’s pom.xml:</em></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.googlecode.jmapper-framework&lt;/groupId&gt;<br>    &lt;artifactId&gt;jmapper-core&lt;/artifactId&gt;<br>    &lt;version&gt;1.6.0.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We are going to define a Bean for object mapping as in the previous case, so we can inject it into our service:</p><pre>@Configuration<br>public class Mapper {<br><br>  @Bean<br>  public JMapper&lt;UserDto,User&gt; userMapper() {<br>    return new JMapper&lt;&gt;(UserDto.class, User.class);<br>  }<br><br>}</pre><p><strong>In order to be able to perform the mapping, JMapper needs an additional aspect to be added in the DTO class</strong>, namely the correspondence between fields of the source and target object.<strong> For this JMapper has 3 different ways to do this: by using JMapperAPI, by using annotations or by XML</strong> configuration. For our example we will use annotations but you can find more information in the following link : (<a href="https://www.baeldung.com/jmapper">https://www.baeldung.com/jmapper</a>.<strong>)</strong></p><p>It is a matter of adding the <strong><em>@JMap</em></strong> annotation to each attribute of the DTO class:</p><pre>@Data<br>public class UserDto implements Serializable {<br><br>  @JMap<br>  private String name;<br>  @JMap<br>  private String surname;<br>  @JMap<br>  private String email;<br>  <br>  @JMap<br>  private List&lt;String&gt; addresses;<br><br>}</pre><p>Once we have everything we need, we just need to inject the Beaninto the service and call the corresponding method offered by JMapper to obtain the UserDtoobject from the Userentity:</p><pre>@Service<br>public class UserService {<br><br>  @Autowired<br>  private UserRepository userRepository;<br><br>  @Autowired<br>  private JMapper&lt;UserDto, User&gt; userMapper;<br><br>  @Transactional(readOnly = true)<br>  public UserDto getUser(Long id) {<br>    return userMapper.getDestination(userRepository.findById(id).orElseThrow(() -&gt; new EntityNotFoundException(&quot;User doesnt exist&quot;)));<br>  }<br><br>}</pre><p>To create custom attribute mappings, simply specify the name of the source attribute in the <strong>@JMap</strong> annotation in the target class. For example, if UserDto has the nombre field corresponding to the namefield of the entity User:</p><pre>@JMap(&quot;name&quot;)<br> private String nombre;</pre><p>📙 Before finishing the post, I want to make special mention to other frameworks that exist such as :</p><ul><li><strong>Orika (</strong><a href="https://www.baeldung.com/orika-mapping">https://www.baeldung.com/orika-mapping</a><strong>)</strong></li><li><strong>Dozer (</strong><a href="https://www.baeldung.com/dozer">https://www.baeldung.com/dozer</a><strong>).</strong></li></ul><p><em>🚨 Besides, I want to show you the following link: </em><a href="https://www.baeldung.com/java-performance-mapping-frameworks"><em>https://www.baeldung.com/java-performance-mapping-frameworks</em></a><em>, which is an in-depth analysis of the different frameworks in terms of performance and efficiency in different situations.</em></p><h3>🏁Conclusion</h3><p>In conclusion, when working with Java mapping frameworks, it’s important to consider factors such as ease of use, performance, and customization options. Choosing the right framework depends on your project’s specific requirements and preferences. By leveraging these frameworks, you can streamline object mapping and enhance the efficiency of your Java applications.</p><p>The use of each framework will depend on the needs of the project or the ease of use found by each user. In this post I have tried to talk about the main frameworks and how to implement them in our project.</p><h4>I hope this post has been useful for you and for those who are starting in this world, I hope it has offered you a different vision of how to do the mapping of attributes between objects. 🎉</h4><h3>HAPPY CODING ! 🎯</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36d68c729e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Streamline Your Database Querying with JPASpecifications and QueryDSL in Spring!]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/streamline-your-database-querying-with-jpaspecifications-and-querydsl-in-spring-421caaabc5bd?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/421caaabc5bd</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 07:58:21 GMT</pubDate>
            <atom:updated>2023-04-26T07:58:21.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgwvB93SfbCKpPo98cT_5A.jpeg" /></figure><p>Fortunately, there are several powerful tools available in the Spring Framework that can help developers overcome these challenges. Two of the most popular are <strong>JPASpecifications and QueryDSL</strong>. Both of these tools provide a <strong>more flexible, type-safe, and secure way </strong>to build database <strong>queries programmatically</strong>, without having to resort to raw SQL.</p><p><em>In this article, we’ll explore the benefits of using JPASpecifications and QueryDSL in Spring applications, how they work, and how you can use them to build more efficient, robust, and maintainable database queries. We’ll also provide code examples to illustrate how to use these tools in your own projects.</em></p><h3><strong>🏁 Starting point</strong></h3><p>To start explaining how JPASpecifications and QueryDSL work and how they can improve our database queries, we need to start with a starting point. In this case, we will use as an <strong>example several JPQL queries using Spring’s derived query methods (we could also have used queries with the Query annotation)</strong> and we will see in the following sections how we can improve them and avoid redundancy in most of them.</p><p>Firstly we define the <strong><em>Product entity</em></strong> with which we will work and with which we will test the different types of database queries :</p><pre>@Entity<br>@Table(name = &quot;products&quot;)<br>public class Product {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br><br>    private String category;<br><br>    private double price;<br><br>    // constructor, getters and setters, etc.<br>}</pre><p>Next, we will define the repository through which we will perform the database queries through Spring Data JPA and the JpaRepository interface. In it, we will define different queries that we will try to refactor later on:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br><br>    List&lt;Product&gt; findByCategory(String category);<br><br>    List&lt;Product&gt; findByCategoryAndPrice(String category, double price);<br><br>    List&lt;Product&gt; findByNameAndCategory(String name, String category);<br><br>    List&lt;Product&gt; findByPriceLessThanEqual(double price);<br><br>    List&lt;Product&gt; findByNameAndPriceGreaterThanEqual(String name, double price);<br><br>}</pre><p>As can be seen, we create different queries according to the business needs and we can see how they grow considerably, where the combination of attributes for each of the queries can grow considerably if we work with an entity with many attributes.</p><p>🚩 Although this approach is really convenient (you don’t even have to write a single line of implementation code to get the queries executed) it has two drawbacks: first,<strong> the number of query methods might grow for larger applications</strong> because of — and that’s the second point —<strong> the queries define a fixed set of criterias</strong>. To avoid these two drawbacks, wouldn’t it be cool if you could come up with a set of atomic predicates that you could combine dynamically to build your query?</p><p>🎯 To solve this problem we will use <strong><em>JPASpecifications and QueryDSL</em></strong>, where we will try to avoid this large number of redundant queries, establishing a series of boolean predicates that we can reuse in each case depending on the database query needs.</p><h3>📕 JpaSpecifications</h3><p>JPASpecifications is an interface that provides methods for constructing <strong>dynamic queries in JPA</strong>. These methods allow the <strong>creation of predicates</strong> that can be used to <strong>filter the results of a query.</strong> For example, a predicate can be built to search for all products with a price greater than a specific value.</p><p>To start working with JPASpecifications it is necessary to refactor the repository defined above. We must indicate that our repository, in addition, extends from JpaSpecificationExecutor :</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt;, JpaSpecificationExecutor&lt;Product&gt; {<br><br>}</pre><p>Once we have extended JpaSpecificationExecutor, we can use the findAll(Specification&lt;T&gt; spec) and findOne(Specification&lt;T&gt; spec)methods to execute queries against JPA specifications. These methods allow us to pass an instance of Specification&lt;T&gt; that defines the search criteria we want to apply to the query, in our case T will be the entity Product.</p><p><strong>A Specification defines a set of conditions that the entities in our database must meet in order to be considered in a query</strong>. Each Specification is an instance of a class that implements the Specification&lt;T&gt; interface, where T is the type of entity we are looking for. For example :</p><pre> public static Specification&lt;Product&gt; hasName(String name) {<br>        return (root, query, criteriaBuilder) -&gt; criteriaBuilder.equal(root.get(&quot;name&quot;), name);<br>    }</pre><p><em>In this example, we are using the Specification class to create a specification that searches for all Product entities whose name attribute matches the parameter passed to the Specification. The specification is built using the </em><em>builder.equals method of the </em><em>CriteriaBuilder class, which allows us to search for an exact match of the name attribute of the Product entity.</em></p><p>Once we have defined the specification, we can use it in our JPA repository to search for entities that meet these search criteria. For example, we can use the findAll(Specification&lt;T&gt; spec) method to search for all Product entities whose name is “T-shirt”:</p><pre>List&lt;Product&gt; products = productRepository.findAll(hasName(&quot;T-shirt&quot;));</pre><p>In this example, we are looking for all Product entities that have the name “T-shirt” in their name attribute. The specification is passed as an argument to the findAll method, which executes the query and returns the results that meet the search criteria defined in the specification.</p><p>In this way we can create a file called <em>ProductSpecifications</em> where we declare the different specifications that we need and that we can reuse in our database queries:</p><pre>public class ProductSpecifications {<br>    <br>    public static Specification&lt;Product&gt; hasName(String name) {<br>        return (root, query, criteriaBuilder) -&gt; criteriaBuilder.equal(root.get(&quot;name&quot;), name);<br>    }<br>    <br>    public static Specification&lt;Product&gt; hasCategory(String category) {<br>        return (root, query, criteriaBuilder) -&gt; criteriaBuilder.equal(root.get(&quot;category&quot;), category);<br>    }<br>    <br>    public static Specification&lt;Product&gt; hasPriceGreaterThan(double price) {<br>        return (root, query, criteriaBuilder) -&gt; criteriaBuilder.greaterThan(root.get(&quot;price&quot;), price);<br>    }<br>    <br>    // ... other search specifications ...<br>    <br>}</pre><p>So, in our service layer we can use these Specifications in combination with the repository or declare directly in repository layer. So <strong>we can reuse these specifications and combine them to get different results from the database</strong>. For example we can retrieve products by their name, by their name and category or by their price greater than the quantity we specify:</p><pre>@Service<br>public class ProductService {<br><br>    private final ProductRepository productRepository;<br>    <br>    public ProductService(ProductRepository productRepository) {<br>        this.productRepository = productRepository;<br>    }<br>    <br>    public List&lt;Product&gt; searchProducts(String name, String category, double minPrice) {<br>        Specification&lt;Product&gt; spec = Specification.where(null);<br>        if (name != null) {<br>            spec = spec.and(ProductSpecifications.hasName(name));<br>        }<br>        if (category != null) {<br>            spec = spec.and(ProductSpecifications.hasCategory(category));<br>        }<br>        if (minPrice &gt; 0) {<br>            spec = spec.and(ProductSpecifications.hasPriceGreaterThan(minPrice));<br>        }<br>        return productRepository.findAll(spec);<br>    }<br>    <br>    // ......<br>    <br>}</pre><p>🐱‍👤If you are curious or just want to know an alternative way to implement this example, have a look at the Query by Example API. (<a href="https://www.baeldung.com/spring-data-query-by-example">https://www.baeldung.com/spring-data-query-by-example</a>)</p><h3>📗 QueryDSL</h3><p>QueryDSL is a library that allows you to build queries in Java programmatically using a syntax similar to SQL. With QueryDSL, it is possible to <strong>create dynamic queries using a wide range of query operations, such as selection, projection, grouping, sorting and joining tables</strong>. The library also provides a complete set of comparison, logical and arithmetic operators, making query creation easier and more readable.</p><p>In order to be able to use <strong>QueryDSL</strong> in our project, we need to add a number of dependencies to our pom.xml :</p><pre>&lt;dependencies&gt;<br>    &lt;!-- ... --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.querydsl&lt;/groupId&gt;<br>        &lt;artifactId&gt;querydsl-jpa&lt;/artifactId&gt;<br>        &lt;version&gt;5.0.0&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.querydsl&lt;/groupId&gt;<br>        &lt;artifactId&gt;querydsl-apt&lt;/artifactId&gt;<br>        &lt;version&gt;5.0.0&lt;/version&gt;<br>        &lt;scope&gt;provided&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>In addition we also have to configure the corresponding plugin:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;com.mysema.maven&lt;/groupId&gt;<br>            &lt;artifactId&gt;apt-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;1.1.3&lt;/version&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;process&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                    &lt;configuration&gt;<br>                        &lt;outputDirectory&gt;target/generated-sources/java&lt;/outputDirectory&gt;<br>                        &lt;processor&gt;com.querydsl.apt.jpa.JPAAnnotationProcessor&lt;/processor&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>This plugin makes sure that the Q-types are generated during the process goal of Maven build. The <em>outputDirectory</em> configuration property points to the directory where the Q-type source files will be generated. The value of this property will be useful later on, when you’ll go exploring the Q-files.</p><p>📌 You should also add this directory to the source folders of the project, if your IDE does not do this automatically — consult the documentation for your favorite IDE on how to do that. For instance, in IntelliJ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Jdjon6Iwg_v2CvaX7F_cFg.png" /></figure><p>You can fix the problem by: <strong>Open <em>target</em> folder → Right click to <em>generated-sources</em> folder -&gt; Mark Directory As -&gt; Generated sources root</strong>.</p><p>As before, it is necessary to refactor the repository defined above. We must indicate that our repository, in addition, extends from QueryDslPredicateExecutor:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt;, QueryDslPredicateExecutor {<br><br>}</pre><p>Once we have all this, we can run : mvn compile to generate the Q-classes. In our case the QProduct class will be generated in <strong><em>target/generated-sources/java</em></strong> and as we have marked this folder as generated-sources-root, we can import this class wherever we need it.</p><p>Once we have the QProduct class generated and we can import it into our project, it’s time to start taking full advantage of it and perform database queries. In this case, QueryDSL uses a more naturally understandable language so we will directly put an example and try to explain how it performs such queries :</p><pre>QProduct product = QProduct.product;<br><br>BooleanExpression hasCategory = product.category.eq(&quot;T-shirt&quot;);<br>BooleanExpression hasName = product.name.eq(&quot;Nike Kids 23452&quot;);<br>BooleanExpression priceGreaterThan = product.price.gt(20.0);<br><br>productRepository.findAll(hasCategory.and(hasName).and(priceGreaterThan);</pre><p>In the first line, a QProduct object is defined which is a QueryDSL-generated class representing the Product entity.</p><p>Then, three BooleanExpression are created using the attributes of the Product entity. The first expression checks if the product has a given category <em>(‘T-shirt’, in this case)</em>, the second expression checks if the product has a given name<em>(‘Nike Kids 23452’, in this case)</em> and the third expression checks if the price of the product is greater than a given value (<em>‘20.0’, in this case)</em>.</p><p>Finally, the productRepository is used to perform a query using the boolean expressions created earlier. The findAll function receives a Boolean expression that is constructed using QueryDSL’s and and or methods to combine the Boolean expressions created earlier. <em>So in the example above, we are querying all products that are T-shirts with the name Nike Kids 23452 and whose price is greater than 20.</em></p><p>In the same way as before, we can define a separate file : ProductConditions where we have all the BooleanExpression as functions where we pass them by parameter values. In this way, as I have seen in the example, with QueryDSL the queries are very simple and understandable and can be nested using AND and OR operators to form the custom queries that we need for each moment of the application.</p><pre>public class ProductConditions {<br><br>    public static BooleanExpression hasCategory(String category) {<br>        QProduct product = QProduct.product;<br>        return product.category.eq(category);<br>    }<br><br>    public static BooleanExpression hasName(String name) {<br>        QProduct product = QProduct.product;<br>        return product.name.eq(name);<br>    }<br><br>    public static BooleanExpression priceGreaterThan(Double price) {<br>        QProduct product = QProduct.product;<br>        return product.price.gt(price);<br>    }<br>}</pre><p><strong>We can then reuse these BooleanExpression definitions wherever and however we need to without having to define new queries that combine some of the entity attributes, as queryDSL provides the AND and OR operators to combine them.</strong></p><pre>productRepository.findAll(ProductConditions.hasCategory(&quot;T-shirt&quot;).and(ProductConditions.hasName(&quot;Nike Kids 23452&quot;)).and(ProductConditions.priceGreaterThan(20.0)));<br><br>productRepository.findAll(ProductConditions.hasCategory(&quot;Jeans&quot;).and(ProductConditions.hasName(&quot;Levis Spring&quot;)));<br><br>productRepository.findAll(ProductConditions.hasName(&quot;Coat ASMR&quot;).or(ProductConditions.priceGreaterThan(60.0)));</pre><h4>Conclusion 🔑</h4><p>In conclusion, JPASpecifications and QueryDSL are powerful tools for creating dynamic and complex queries in Spring.</p><p>JPASpecifications allow us to encapsulate query conditions into reusable Specification objects, providing a way to compose queries dynamically at runtime. By using JPASpecifications, we can write cleaner, more modular code that is easier to maintain and extend.</p><p>On the other hand, QueryDSL offers a type-safe way to construct and execute SQL-like queries in Java. By using QueryDSL, we can generate type-safe queries, reducing the risk of runtime errors and improving performance by avoiding unnecessary SQL parsing and parameter binding.</p><p>Both JPASpecifications and QueryDSL can help us avoid multiple redundant queries and improve the performance of our application. Additionally, they can help us write more concise and readable code, making it easier to understand and maintain our data access layer.</p><p>In summary, JPASpecifications and QueryDSL are valuable tools for developers working with Spring and SQL databases, providing a way to create dynamic and efficient queries in a type-safe, modular, and reusable way.</p><h4>I hope this post will help you to know more about another great aspect that Spring offers us, in this case related to database queries.</h4><h4>Happy Coding!🎯</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=421caaabc5bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Bean Scopes in Spring: Which One is Best for Your Application?]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/understanding-bean-scopes-in-spring-which-one-is-best-for-your-application-3ff404e44b76?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff404e44b76</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[beans]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 09:15:41 GMT</pubDate>
            <atom:updated>2023-04-16T09:15:41.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBr4WyRPCdvAtWNFvkxArA.jpeg" /></figure><p>Beans are fundamental components in Spring framework that are managed by the Spring container. They represent objects that are created, configured, and managed by the Spring framework to provide various functionalities in a Spring application. One important aspect of <strong>beans in Spring is their</strong> <strong>scope</strong>, <strong>which determines how they are instantiated and managed by the container.</strong></p><p>In this post, we will delve into the world of bean scopes in Spring and clarify the concept behind different scopes, such as <em>Singleton, Prototype, and other less commonly used scopes</em>. We will explore their behaviors, advantages, and use cases, to help you make informed decisions when choosing the appropriate scope for your beans in your Spring applications.</p><p><em>Whether you are a Spring beginner or an experienced developer, this comprehensive guide will provide you with a clear understanding of bean scopes in Spring and help you optimize your application’s performance and memory usage.</em></p><p>So, let’s dive in and uncover the secrets of bean scopes in Spring!</p><h4>🔊 Introduction</h4><p>Spring beans can have different <strong>scopes that indicate how their lifecycle and availability will be managed in the context of the application</strong>. Some of the most common scopes for Spring beans are:</p><ul><li><strong>Singleton</strong></li><li><strong>Prototype</strong></li><li><strong>Request</strong></li><li><strong>Session</strong></li><li><strong>Application</strong></li><li><strong>WebSocket</strong></li></ul><p>These are some of the most common scopes in Spring, but there are also other custom scopes that can be defined according to the specific needs of an application. Choosing the right scope for a bean in Spring depends on the requirements of the application and the desired lifecycle of the managed object. We will explain each of them in more detail below.</p><h3>🎲 Singleton</h3><p>When a bean has a singleton scope, it means that <strong>only a single instance of the bean is created per Spring application context</strong>. This instance is stored in memory and reused each time the bean is requested in the future, rather than creating a new instance for each request.</p><pre>@Component<br>@Scope(&quot;singleton&quot;)<br>public class SingletonBean {<br>   <br>}</pre><p>Here are some key features of the singleton scope in Spring:</p><ul><li><strong>Single instance</strong>: Only one instance of the bean is created in the entire Spring application lifecycle. Each time the bean is requested, the same previously created instance is returned, if it already exists.</li><li><strong>Stored in memory</strong>: The bean instance is stored in memory, which means that it persists for the lifetime of the application and is available for use at any time.</li><li><strong>Shared</strong>: The same singleton bean is shared between different components or classes that inject it into their Spring application context. This can have implications for concurrency and bean state, so care must be taken when handling shared data in singleton beans.</li><li><strong>Efficienc</strong>y: Using singleton beans can improve the efficiency and performance of the application by avoiding the overhead of creating multiple instances of the same bean for each request.</li></ul><p>🚩<strong> It is important to note that the singleton scope in Spring is the DEFAULT scope for beans, so if no scope is specified, it is considered as singleton. However, care should be taken when using singleton beans in concurrent or stateful applications, as this can have implications for concurrency and state integrity.</strong></p><h3>🧱 Prototype</h3><p>When a bean has a prototype scope, it means th<strong>at a new instance of the bean is created each time it is requested</strong>. Unlike the singleton scope, where a single instance of the bean is created and reused, in the prototype scope a new instance of the bean is created on each request.</p><pre>@Component<br>@Scope(&quot;prototype&quot;)<br>public class PrototypeBean {<br>   <br>}</pre><p>Here are some key features of the prototype scope in Spring:</p><ul><li><strong>New instance on each request</strong>: Each time a bean with “prototype” scope is requested, a new instance of the bean is created. This means that each time the bean is injected or fetched, a new instance will be fetched.</li><li><strong>No state sharing</strong>: Bean instances with prototype scope do not share their state with other bean instances. Each instance has its own independent state and any modification to one bean instance will not affect other instances.</li><li><strong>Unmanaged lifecycle</strong>: Unlike other scopes such as singleton or session, bean instances with “prototype” scope are not managed completely by the Spring container. This means that Spring does not take care of destroying prototype bean instances when they are no longer in use. It is the responsibility of the developer to manage the lifetime of prototype bean instances and release resources appropriately.</li><li><strong>Greater configuration flexibility</strong>: The prototype scope is more flexible in terms of configuration, as it allows multiple instances of the same bean to be created with different configurations or parameters at runtime.</li><li><strong>Higher resource consumption</strong>: Because a new instance of the bean is created for each request, the use of prototype scoped beans may result in higher resource consumption compared to other scopes such as singleton or request, as more instances are created and destroyed.</li><li><strong>Suitable for objects with changing state</strong>: The prototype scope is suitable for beans whose state changes frequently and there is no need to share state between different instances.</li></ul><p>It is important to note that prototype scoping in Spring can be useful in situations where you need a <strong>new instance of the bean on every request</strong>, and you want to have <strong>more flexibility in state and concurrency management</strong>. However, you should also be aware of the<strong> increased computational cost associated</strong> with creating new instances on each request.</p><blockquote>In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The container instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up. (<a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes-prototype">https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes-prototype</a>)</blockquote><p>As a rule, you should use the prototype scope for all stateful beans and the singleton scope for stateless beans.</p><h3>📩 Request</h3><p>When a bean has a request scope, it means that a<strong> new instance of the bean is created for each HTTP request that arrives at the server</strong>. This instance of the bean will be available for the duration of the processing of that specific request, and will be destroyed at the end of the request.</p><pre>@Component<br>@RequestScope<br>public class RequestBean {<br>    <br>}</pre><p>Here are some key features of the scope request in Spring:</p><ul><li><strong>One instance per request</strong>: Each time a web request arrives at the server, a new instance of the bean with scope request is created for that specific request. This allows to have a specific state for each request and avoid sharing information between different requests.</li><li><strong>In-request state sharing</strong>: Bean instances with request scope share their state within the context of the request in which they were created. This means that all components or classes accessing the same bean in the same request will see the same state of the bean.</li><li><strong>Suitable for request-specific data</strong>: The request scope is suitable for beans that contain HTTP request-specific data, such as user information, request parameters, or request-specific session data.</li><li><strong>Limited to request context</strong>: Bean instances with request scope are only accessible within the context of the request in which they were created. They cannot be accessed from other requests or outside the context of the current request.</li><li><strong>Useful in web applications</strong>: The request scope is especially useful in web applications, where you need to have a specific bean instance for each request and you want to share the same bean between different components within the same request lifecycle.</li></ul><p>It is important to note that the Spring request scope only makes sense in the context of web applications, and will only be available in the context of a web request that is handled by a Spring framework, such as Spring MVC. In addition, care should be taken when handling shared data in beans with scope request, as it can have implications on concurrency and state integrity in applications with multiple concurrent requests.</p><h3>🔑 Session</h3><p>When a bean has a session scope, it means that <strong>a single instance of the bean is created for each HTTP session that is established in the application.</strong> This instance of the bean will be available for the duration of the user’s session, and will be destroyed at the end of the session.</p><pre>@Component<br>@SessionScope<br>public class SessionBean {<br>    <br>}</pre><p>Here are some key features of the session scope in Spring:</p><ul><li><strong>One instance per session</strong>: Each time a user logs into the web application, a new instance of the bean with scope “session” is created for that specific session. This instance of the bean will be available for the duration of the user’s session, and will be destroyed at the end of the session.</li><li><strong>In-memory storage during the session</strong>: The bean instance with scope “session” is stored in memory for the duration of the user’s session. This allows to have a specific state for each user session and to keep the session-related information persistent during the user’s navigation in the application.</li><li><strong>If a user logs out or the session expires, the bean instance is automatically destroyed</strong>. This allows for automated management of bean instances based on the lifecycle of the user’s session.</li><li><strong>The session scope is available only in Spring MVC-based web applications</strong>, as it refers to the management of instances in the context of an HTTP session.</li><li><strong>Shared within the same session</strong>: The same bean with scope “session” is shared between different components or classes that inject it in the context of the same user session. This allows the same instance of the bean to be accessed in different parts of the application during the same user session.</li><li><strong>Useful in web applications</strong>: The session”scope is especially useful in web applications, where specific user session information needs to be maintained, such as authentication data, user preferences or session state.</li></ul><p>It is important to note that the session scope in Spring only makes sense in the context of web applications based on user session technologies, such as HTTP sessions. In addition, concurrency management and security need to be taken into account when handling shared data in beans with session scope, as they may have implications on the integrity and privacy of user session information.</p><h3>🎭 Application</h3><p>The application scope in Spring can be used to define <strong>beans whose instances are intended to be shared globally throughout the application</strong>, meaning that they can be accessed from anywhere in the application at any time.</p><pre>@ApplicationScope<br>@Component<br>public class ApplicationBean{<br>   <br>}</pre><p>Some features of the application scope are:</p><ul><li><strong>A bean instance is created at the start of the application</strong> and is maintained for the lifetime of the application. This means that there will only be a single instance of the bean in the entire application, and all parts of the application will access the same instance.</li><li><strong>The bean instance is stored in a global scope and can be accessed from any part of the application</strong>. This allows sharing global data or functionality in the application, such as configurations, utilities, cache objects, and so on.</li><li><strong>The Application scope is useful to define beans that need to be shared between multiple components</strong>, services or controllers in a Spring application, and that need to maintain a global state and be accessible from any part of the application.</li><li><strong>The use of application scoping should be careful</strong> and consider the impact on performance and scalability, as the bean instance is kept in memory for the lifetime of the application, which may consume server resources.</li></ul><h4>🧨 Singleton vs Application Scope</h4><p>A ServletContext is shared between all servlets living on the same servlet container (e.g. Tomcat). This is a Java EE class (it belongs to the package javax.servlet).<strong> Beans annotated with </strong><strong>@ApplicationScope are bounded to the ServletContext.</strong></p><p>An ApplicationContext represents a Spring IoC container, so it is a Spring-specific class (it belongs to the package org.springframework.context). Si<strong>ngleton scoped beans are bounded to the ApplicationContext.</strong></p><p>You can have multiple IoC container in the same servlet container, so you can have multiple singleton beans of the same type but only one application scoped bean of each type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*1rLDhtXdn5f5oyl3.jpg" /></figure><h3>🔐 WebSocket</h3><p>The WebSocket Scope type is a special type in which the bean that is created lasts for the duration of the WebSocket session.</p><p>This Scope type is used to create WebSocket applications, for example for bidirectional message exchange between client and server. This type of Scope will live as long as the WebSocket session is alive. We can also say that it exhibits singleton behavior, but limited to a <em>WebSocket</em> session only.</p><pre>@Component<br>@Scope(scopeName = &quot;websocket&quot;, proxyMode = ScopedProxyMode.TARGET_CLASS)<br>public class WebSocketBean{<br><br>}</pre><p>The request, session, application, and websocket scopes are available only if you use a Web-Aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers, such as the ClassPathXmlApplicationContext, an IllegalStateException that complains about an unknown bean scope is thrown.</p><h4>📌Conclusion</h4><p>In conclusion, the bean scopes in Spring are an important feature that allows you to control the lifespan and visibility of bean instances in your application. Understanding the different scopes, such as singleton, prototype, request, session, and application, is crucial for managing the state and behavior of beans based on your application’s requirements. Choosing the right scope for your beans can help you optimize the performance and memory usage of your Spring application. It’s important to carefully consider the scope of your beans based on your application’s architecture, concurrency requirements, and data sharing needs to ensure that your beans behave as expected and meet your application’s functional and performance requirements.</p><h4>I hope this overview of the different bean scopes in Spring has been helpful in understanding their characteristics and best use cases.</h4><h3>Happy coding! 🎯</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff404e44b76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn to use RestTemplate Interceptor: Configuration and Use Cases!]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/learn-to-use-resttemplate-interceptor-configuration-and-use-cases-bd59200afcb0?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd59200afcb0</guid>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[resttemplate]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 11:36:46 GMT</pubDate>
            <atom:updated>2023-04-11T11:37:29.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrlUZN-hMuG7sEhbCGfiHQ.png" /></figure><p>RestTemplate is a widely used client-side HTTP communication library in Spring applications,<strong> allowing developers to make RESTful API calls</strong> with ease. However, sometimes you need to customize the behavior of these requests, such as adding <strong>logging, authentication, error handling, or other customizations</strong>. This is where RestTemplate Interceptor comes into play! RestTemplate Interceptor is a powerful feature that allows you to i<strong>ntercept and modify HTTP requests and responses</strong> before they are sent or processed, giving you fine-grained control over your API calls. In this article, we will explore the ins and outs of RestTemplate Interceptor, and learn how you can leverage its capabilities to streamline your HTTP requests, enhance security, and optimize your API interactions in your Spring applications. Join us as we dive into the world of RestTemplate Interceptor and unlock its full potential for your RESTful API integrations!</p><p><em>In this article we will learn how to configure our RestTemplate and associate it with the Interceptor that we will create during this post. In our case, we will use the interceptor for logging but it can be focused on multiple other uses as we have discussed previously. </em>🧠</p><h3>⚙ Configuring RestTemplate with an Interceptor</h3><p>First of all, we must configure our RestTemplate to be able to inject it into the part of the project where we want to make REST API calls to another service, either internal or external to our architecture. To do this we need to create a Spring configuration class : <strong>RestTemplateConfig</strong>, so that our class is decorated with the<strong> @Configuration annotation</strong>.</p><pre>@Configuration<br>public class RestTemplateConfig {<br><br>}</pre><p><strong><em>The @Configuration annotation on a Spring class indicates that the class is a Spring configuration and defines a bean or several beans in the context of the application.</em></strong><em> </em><strong><em>A bean in Spring is an object managed by the Spring container that can be used in other parts of the application.</em></strong></p><p><em>A class annotated with @Configuration may contain one or more methods annotated with @Bean, which are used to define and configure the beans in the context of the application. These methods can perform the necessary configuration, such as creating object instances, setting properties, setting dependencies, and returning objects that will become Spring-managed beans.</em></p><p>Within this configuration class, we are going to create our Bean that declares an instance of RestTemplateand that will be, by default (if no other beans are declared), the one that injects into our project.</p><pre><br>@Configuration<br>public class RestTemplateConfig {<br><br>  @Bean<br>  public RestTemplate restTemplate() {<br>    final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new<br>        SimpleClientHttpRequestFactory()));<br><br>    restTemplate.setInterceptors(Collections.singletonList(new RestTemplateFilter()));<br>    return restTemplate;<br>  }<br>}</pre><p>As you can see in the code above, we have declared the bean for RestTemplate and we have associated the<strong> interceptor </strong>RestTemplateFilter to it, which we will declare and detail below depending on the use we want to give it.</p><p>At this point we must emphasize the initialisation of the RestTemplate :</p><pre>final RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new<br>        SimpleClientHttpRequestFactory()));</pre><blockquote><strong>If we want our interceptor to function as a request/response logger, then we need to read it twice — the first time by the interceptor and the second time by the client.</strong></blockquote><blockquote>The default implementation allows us to read the response stream only once. To cater such specific scenarios, Spring provides a special class called BufferingClientHttpRequestFactory. As the name suggests, this class will buffer the request/response in JVM memory for multiple usage.</blockquote><p><strong>🚩If we don’t initialise Rest Template</strong> with the BufferingClientHttpRequestFactoryclass, we will get an OK response to our requests but <strong>we will get a null value for the response body.</strong></p><h3>📢 RestTemplate Interceptor For Logging</h3><p>Next we are going to define the Interceptor, for this we have to create a class, which we will call in our case RestTemplateFilter, which has to extend ClientHttpRequestInterceptor. Then we have to overwrite the intecept method, which is called before an HTTP request is sent and after the HTTP response is received. In this method, the HTTP request is logged, including the HTTP method, URI and request body (if any), as well as the HTTP response, including status code, status text and response body (if any). Log messages are logged using a logging library such as SLF4J.</p><pre><br>import java.io.IOException;<br>import java.nio.charset.StandardCharsets;<br>import java.util.Arrays;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.http.HttpRequest;<br>import org.springframework.http.client.ClientHttpRequestExecution;<br>import org.springframework.http.client.ClientHttpRequestInterceptor;<br>import org.springframework.http.client.ClientHttpResponse;<br><br><br>public class RestTemplateFilter implements ClientHttpRequestInterceptor {<br><br>  private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateFilter.class);<br><br>  @Override<br>  public ClientHttpResponse intercept(HttpRequest request, byte[] body,<br>      ClientHttpRequestExecution execution) throws IOException {<br><br>    LOGGER.info(&quot;RestTemplate does a http/s to - {} with HTTP Method : {}&quot;, request.getURI(), request.getMethodValue());<br><br>    ClientHttpResponse response = execution.execute(request, body);<br><br>    if (response.getStatusCode().is4xxClientError() || response.getStatusCode()<br>        .is5xxServerError()) {<br>      LOGGER.error(&quot;RestTemplate received a bad response from : {} - with response status : {} and body : {} &quot;,<br>      request.getURI(), response.getRawStatusCode(), new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8));<br>    } else {<br>      LOGGER.info(&quot;RestTemplate received a good response from : {}- with response status {}&quot;,<br>          request.getURI(),<br>          response.getRawStatusCode());<br>    }<br><br>    return response;<br>  }<br>}</pre><p>In the code above, we can see that we are logging both the URI and the HTTP method of the incoming request. Subsequently, the request : ClientHttpResponse response = execution.execute(request,body)is executed and we log the response data, both the URI and the status code, plus the response body in case we get a response with an error code.</p><p>In conclusion, interceptors in Spring’s RestTemplate provide a powerful mechanism to intercept and modify HTTP requests and responses in a flexible and customizable way. They can be used for various purposes such as logging, authentication, caching, error handling, and more. By implementing the ClientHttpRequestInterceptorinterface, developers can define their own logic to be executed before and after making HTTP requests using RestTemplate. This allows for additional processing and customization of HTTP interactions within an application. Interceptors offer a powerful tool for enhancing the functionality and behavior of RestTemplate, making it a valuable component in building robust and reliable RESTful web service clients in Spring applications. 🎁</p><h4><strong>We hope this article has provided you with a clear understanding of how interceptors work in RestTemplate and how they can be used to improve your RESTful web service clients in Spring. So go ahead and start implementing interceptors in your RestTemplate configuration to unlock the full potential of this powerful tool!</strong></h4><h3><strong>Happy coding! 🎯</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd59200afcb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Spring: Constructor, Property, or Setter? Which one should I choose?]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/dependency-injection-in-spring-constructor-property-or-setter-which-one-should-i-choose-d38be824c8c1?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38be824c8c1</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 08:54:26 GMT</pubDate>
            <atom:updated>2023-04-05T08:54:26.503Z</atom:updated>
            <content:encoded><![CDATA[<h3>💉Dependency Injection in Spring: Constructor, Property, or Setter? Discover the Best Option for Your Project!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ek29maeClqwXUQ5Q.jpeg" /></figure><p><em>Dependency injection is a programming technique in which objects are created with all the dependencies they need to function properly, rather than creating those dependencies within the object.</em></p><p><strong>Dependency Injection is a key feature of the Spring Framework, allowing for loosely coupled, reusable code</strong>. But with multiple ways to inject dependencies in Spring, it can be challenging to know which approach to use for your project. In this article, we’ll explore the three primary Dependency Injection techniques in Spring. We’ll discuss the benefits and drawbacks of each approach, and provide guidance on when to use each method.</p><p>In the Spring Framework, there are three main dependency injection techniques: <strong>Constructor Based Dependency Injection</strong>, <strong>Field or Property-Based Dependency Injection</strong> (@Autowired in a variable) and <strong>Setter Based Dependency Injection</strong>. We will now discuss which of these techniques is the best option in different situations.</p><p>By the end of this article, you’ll have a solid understanding of how to choose the best Dependency Injection technique for your specific Spring project.</p><h3>🧱 Constructor Based Dependency Injection</h3><p>Constructor Based Dependency Injection is the <strong>most recommended</strong> dependency injection technique in the Spring Framework. This technique involves passing all necessary dependencies for an object as arguments to the constructor. The object is created only after all necessary dependencies have been provided.</p><p>The main reason for preferring dependency injection through the constructor is that it allows dependencies to be explicit and mandatory. This means that all dependencies necessary for an object to function correctly must be provided at object creation time, which ensures that the object is in a valid state from the start. In addition, injecting dependencies through the constructor makes the <strong>code easier to understand and maintain</strong>, as all dependencies required for the object are clearly defined in the constructor.</p><p>Let’s look at an example:</p><pre>public class ProductService {<br>   private final ProductRepository productRepository;<br>  <br>   public ProductService(ProductRepository productRepository) {<br>      this.productRepository = productRepository;<br>   }<br>}</pre><p>In this example, the ProductService class has a dependency on ProductRepository , which is passed as an argument in the constructor.</p><p>In the example I mentioned above, you don’t need to use the @Autowired annotation when using dependency injection through the constructor. This is because<strong> Spring Framework can automatically detect</strong> the constructor with arguments and provide the corresponding dependency instances at runtime.</p><p>So, in the example I showed, Spring Framework will detect that the ProductServiceclass has a constructor with an argument of type ProductRepository, and will look for a bean of type ProductRepositoryto inject. Since the ProductRepositoryis defined as a bean in the Spring context, an instance of ProductRepositorywill be created and injected into the constructor of ProductService.</p><p>Besides the finalkeyword is used to declare the variable productRepositoryas a constant. This way, once a value is assigned in the constructor, the variable cannot be reassigned to another object.</p><p>The use of the finalkeyword is optional when injecting dependencies through the constructor, but it is a good programming practice because it helps ensure the immutability and consistency of objects. By making a variable final, you avoid accidentally changing its value in other parts of the code.</p><p>Therefore, although the use of finalis not mandatory when injecting dependencies through the constructor, its use is strongly recommended whenever possible. Furthermore, it is also important to note that dependency injection through the constructor works regardless of whether the variable is final or not.</p><h4>Tip ✨</h4><p>When using this type of dependency injection we can rely on the <strong>Lombok</strong> library, which offers us the @RequiredArgsConstructor annotation that simplifies the code and saves us from generating the class constructor with the different necessary parameters.</p><pre>import lombok.RequiredArgsConstructor;<br><br>@Service<br>@RequiredArgsConstructor<br>public class ProductService {<br>    private final ProductRepository productRepository;<br>}</pre><p>In this example, Lombok will automatically generate a constructor that takes a ProductRepositoryargument and assigns it to the productRepositoryvariable. There is no need to write the constructor manually, which reduces the amount of code that needs to be written.</p><p>It is important to note that Lombok uses the @NotNull annotation for fields in the class that are declared as final, which means that the field cannot be null. If the argument passed to the constructor is null, a NullPointerExceptionwill be raised.</p><h3>🧩 Field or Property-Based Dependency Injection</h3><p>Property-Based Dependency Injection(@Autowired on a variable) involves annotating a property with the @Autowired annotation. When Spring creates an object that has a property annotated with @Autowired, Spring looks up an instance of the corresponding dependency and assigns it to the property.</p><p>Injecting dependencies through properties can make dependencies optional, which means that the object may be in an invalid state until all dependencies are set. This can cause run-time errors and make it difficult to identify the root cause of the problem.</p><p>Let’s look at an example:</p><pre>public class ProductService {<br><br>   @Autowired<br>   private ProductRepository productRepository;<br>}</pre><p>In this example, the ProductServiceclass has a dependency on ProductRepository, which is injected through the productRepositoryproperty annotated with (@Autowired).</p><h3><strong>🎯 Setter Based Dependency Injection</strong></h3><p>Setter Based Dependency Injection involves annotating a method with the @Autowired annotation. When Spring creates an object that has a method annotated with @<em>Autowired</em>, Spring looks up an instance of the corresponding dependency and assigns it to the method parameter.</p><p>Like the previous one, Setter-based injection can be useful in situations where optional properties are needed or when it is difficult to modify the constructor of an existing class. However, it also has some disadvantages.</p><p>One of the main disadvantages of setter-based injection is that it can lead to objects in an inconsistent state if all required dependencies are not established. This can be problematic because the object may not function correctly if methods are used before all dependencies have been established.</p><p>Another disadvantage is that setter-based injection can make it difficult to understand the dependencies of an object in the code, since the dependencies are not explicitly specified in the constructor. This can make it more difficult to follow the flow of control through the code.</p><p>Let’s look at an example:</p><pre>public class ProductService {<br>   private ProductRepository productRepository;<br>  <br>   @Autowired<br>   public void setProductRepository(ProductRepository productRepository) {<br>      this.productRepository = productRepository;<br>   }<br>}</pre><p>In this example, the ProductServiceclass has a dependency on ProductRepository, which is injected through the setProductRepository() method annotated with (@Autowired).</p><h3>🧠 Choosing a Dependency Injection Technique</h3><p>Now that we have covered the three main dependency injection techniques in the Spring Framework, how do we choose which one to use? In general, it is recommended to use dependency injection through the constructor whenever possible. This makes dependencies explicit and mandatory, leading to cleaner code that is easier to understand and maintain. In addition, injecting dependencies through the constructor avoids the potential problems of property or method-based dependency injection techniques.</p><p>However, there are cases where dependency injection through properties or setters can be useful. For example, if you have a class with many dependencies and you want to keep your code more readable, it may be useful to inject dependencies through properties instead of a constructor with many arguments. It may also be useful to use dependency injection through methods if you want to establish the dependency after the object is created.</p><p><em>In summary, dependency injection via the constructor is the most recommended dependency injection technique in the Spring Framework. Dependency injection techniques based on properties and setters can be useful in certain situations, but it is important to be aware of the potential problems that may arise. By choosing the right dependency injection technique, you can ensure that your code is clean, easy to understand and maintain, and in a valid state from the start.</em></p><h4>I hope this post will help you to better understand the different types of dependency injection and to write much more readable code with good practices. Happy coding! 🚀🎉</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38be824c8c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud 2022.0.2 is Here: What’s New for Developers?]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/spring-cloud-2022-0-2-is-here-whats-new-for-developers-e2c9136e9bf?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c9136e9bf</guid>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 08:57:11 GMT</pubDate>
            <atom:updated>2023-04-03T08:57:11.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*SBc1Zk2FZP5WD2-7fXMbsQ.png" /></figure><p>Exciting news for developers: Spring Cloud 2022.0.2 has arrived with a whole new set of features and tools to make your life easier. If you’re not already familiar with Spring Cloud, it’s a framework that provides developers with a wide range of tools for building scalable and resilient applications. And with this latest release, the Spring team has added even more functionality to help developers streamline their work and optimize their applications.</p><p>In this article, we’ll dive into the latest release of Spring Cloud and explore all the exciting new features it brings. Whether you’re a seasoned pro or just starting out, there’s something for everyone in this update. So, get ready to discover all the ways that Spring Cloud 2022.0.2 can help you take your development game to the next level!</p><p>The release can be found on Maven Central. You can check the 2022.0.2 release notes for more information on the official Spring website or at the following link:</p><p><a href="https://github.com/spring-cloud/spring-cloud-release/wiki/Spring-Cloud-2022.0-Release-Notes#202202">Spring Cloud 2022.0 Release Notes</a></p><h3>🧠 What is Spring Cloud?</h3><p>Spring Cloud is an open-source framework designed to simplify the development of distributed cloud applications. It provides developers with a wide range of tools and libraries to help them build scalable and resilient microservices-based applications that can run on any cloud platform.</p><p>Spring Cloud is used to handle common challenges associated with developing distributed applications, such as service discovery, load balancing, configuration management, and fault tolerance. It also provides a variety of other features, such as distributed tracing and security, to help developers build robust and secure cloud applications.</p><p>Spring Cloud builds on top of the Spring Boot framework and integrates with other Spring projects to provide a comprehensive suite of tools for building cloud-native applications. Whether you’re developing a small-scale application or a large-scale distributed system, Spring Cloud can help you build better, more scalable, and more resilient cloud applications.</p><h3>🆕 What’s new in Spring Cloud 2022.0.2?</h3><p>Below we are going to detail the changes of this new version in the different modules that make up Spring Cloud and that have been affected by this new release .</p><p>In general the following modules were affected in this new update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Fp6IG7aCwhVaJpDlp25xuQ.png" /></figure><p>But we will focus only on those whose new changes involve new features at the code developer level.</p><h4>Spring Cloud Kubernetes:</h4><ul><li>Added support for external name services using the Fabric8 DiscoveryClient</li><li>Add Pod metadata and annotations to ServiceInstance</li></ul><h4>Spring Cloud OpenFeign:</h4><ul><li>Register native reflection hints for user-provided parameters and return types</li><li>Support setting FeignClient URL in runtime for native images</li><li>Allow setting protocols for underlying OKHttp client</li><li>Add the possibility to use factory beans for Fallback</li></ul><h4>Spring Cloud Gateway:</h4><ul><li>The global cache can now be disabled when using Local Response Cache</li></ul><h4>Spring Cloud Commons:</h4><ul><li>Allow emitting healthcheck instances in batches</li></ul><h4>Spring Cloud Contract:</h4><ul><li>Allow sendMessage to handle body from file</li><li>Relaxed SSL validation with RestTemplate interceptors</li></ul><p>Apart from the changes mentioned above, this new version covers different bugs in the different modules that make up Spring Cloud. More information about them can be found in the task list in the Spring Cloud Github:</p><p><a href="https://github.com/orgs/spring-cloud/projects/104/views/1">2022.0.2 * spring-cloud</a></p><h4>We hope this article has been helpful in giving you a taste of what’s new in Spring Cloud 2022.0.2. As always, we encourage you to explore the documentation and try out the new features for yourself. Happy coding! 🚀</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c9136e9bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Truth about Java Parameter Passing : Is It Pass-by-Value or Pass-by-Reference? ]]></title>
            <link>https://medium.com/@miguelangelperezdiaz444/the-truth-about-java-parameter-passing-is-it-pass-by-value-or-pass-by-reference-cc58d3b249a9?source=rss-6020d06ec40c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc58d3b249a9</guid>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[datatypes-in-java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[pass-by-value]]></category>
            <dc:creator><![CDATA[Miguel Angel Perez Diaz]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 09:38:00 GMT</pubDate>
            <atom:updated>2023-03-29T14:37:28.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*tdneIh5NoV3Fe_BOV7xRBQ.png" /></figure><h3>The Truth about Java Parameter Passing : Is It Pass-by-Value or Pass-by-Reference? 🎭</h3><p>Java is a popular object-oriented programming language that has been around for over two decades. One of the fundamental concepts in Java is parameter passing, which refers to the mechanism by which arguments are passed to methods. However, the question of whether Java passes parameters by value or by reference is a topic of much debate and confusion among developers. While Java is commonly said to be pass-by-value, the reality is that it behaves differently depending on the type of the parameter being passed. In this article, we’ll explore the intricacies of Java parameter passing, discussing the differences between pass-by-value and pass-by-reference and how they manifest in Java. We’ll also examine the behavior of objects, primitives, and wrapper classes, as well as some common misconceptions about Java parameter passing. By the end of this article, you’ll have a better understanding of this important concept in Java programming.</p><h4>Firstly, but what does pass-by-value and pass-by-reference mean?</h4><p>In programming languages, there are two common ways of passing parameters to methods or functions: pass-by-value and pass-by-reference.</p><p><strong>In pass-by-value, a copy of the value of the parameter is passed to the method or function</strong>. This means that any changes made to the parameter within the method or function do not affect the original value of the parameter outside the method or function. In other words, the method or function works with a local copy of the parameter’s value, and any changes made to that copy do not affect the original value of the parameter.</p><p><strong>In pass-by-reference, a reference to the parameter is passed to the method or function</strong>. This means that any changes made to the parameter within the method or function affect the original value of the parameter outside the method or function. In other words, the method or function works directly with the parameter itself, and any changes made to the parameter are reflected in the original value of the parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ENXUq7WnjPVJbSgR.gif" /></figure><p>There has always been a lot of controversy about this topic in Java and although the theory says that Java always passes parameters by value, we are going to explain how it behaves depending on the type of data that is passed as an argument. <br>We can find mainly 2 types of data:<strong> primitive</strong> and <strong>non-primitive.</strong></p><p>Within the primitive data we can find the following types : <strong>boolean, byte, int, short, double, long, float</strong> and <strong>char.</strong></p><p>As for non-primitive data we can talk about :<strong> String, Array, List (any predefined data structure)</strong> and <strong>classes wrappers of primitive types (Boolean, Integer, Double, etc)</strong></p><h3>Primitive Data Types</h3><p>Primitive data is passed to methods or functions by value and behaves in the way we have previously discussed <strong>(if we modify its value within the method, the original variable is not altered)</strong>.</p><pre>public class Main {<br>  public static void main(String[] args) {<br>    int x = 10;<br>    System.out.println(&quot;Before calling the method: &quot; + x);<br>    changeValue(x);<br>    System.out.println(&quot;After calling the method: &quot; + x);<br>  }<br><br>  public static void changeValue(int value) {<br>    value = 20;<br>    System.out.println(&quot;Within the method: &quot; + value);<br>  }<br>}</pre><p>The results are as follow :</p><p><strong><em>Before calling the method: 10<br>Within the method: 20<br>After calling the method: 10</em></strong></p><h3>Non-Primitive Data Types</h3><p>This is where we find the greatest controversy within the Java community and it is where we will delve deeper to clarify these concepts. To try to explain these concepts we are going to use the same example as before but in this case passing a non-primitive data type as an argument and we will see how the function behaves :</p><pre>public class Main {<br>  public static void main(String[] args) {<br>    Person p = new Person(&quot;John&quot;, 20);<br>    System.out.println(&quot;Before calling the method: &quot; + p);<br>    changeName(p);<br>    System.out.println(&quot;After calling the method: &quot; + p);<br>  }<br><br>  public static void changeName(Person person) {<br>    person.setName(&quot;Peter&quot;);<br>    System.out.println(&quot;Within the method: &quot; + person);<br>  }<br>}<br><br>class Person {<br>  private String name;<br>  private int age;<br><br>  public Person(String name, int age) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  public String getName() {<br>    return name;<br>  }<br><br>  public void setName(String name) {<br>    this.name = name;<br>  }<br><br>  public int getAge() {<br>    return age;<br>  }<br><br>  public void setAge(int age) {<br>    this.age = age;<br>  }<br><br>  @Override<br>  public String toString() {<br>    return &quot;Person [name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;<br>  }<br>}</pre><p>The results are as follow :</p><p><strong><em>Before calling the method: Person [name=John, age=20]<br>Within the method: Person [name=Peter, age=20]<br>After calling the method: Person [name=Peter, age=20]</em></strong></p><p>Looking carefully at the example, we can think that I am wrong, if I said before that Java always passes by value the arguments and these are not modified, why this type of data are being modified within the function? We can explain this in the following way:</p><p>Java passes objects by value, which means that a <strong>copy of the reference to the object</strong> is passed, not a copy of the object itself<strong>. This reference is a memory address that points to the actual object</strong>. When an object is passed to a method, a copy of the reference is passed, <strong>which means that both (the copy and the original) point to the same object in memory</strong>. Therefore, when you modify the object within the method, you are making changes to the actual object that both references point to.</p><p>For example, if you pass an object of type List to a method and add an item to the list within the method, you are modifying the actual object to which both references point. Although the reference passed to the method is a copy, both references point to the same real object in memory, so any changes made within the method will affect the real object.</p><p>It is important to note that although objects are passed by value in Java, the behaviour may be different <strong>depending on the type of object</strong> and how it is manipulated within the method. For example, if a copy of a <strong>immutable object</strong> <strong><em>(like a String) </em></strong>is passed to a method, the copy and the original object may point to different objects in memory, meaning that any modifications made within the method will only affect the copy and not the original object. Therefore, it is important to have a good understanding of how objects work in Java and how they are manipulated within methods.</p><p>In conclusion, Java passes parameters by value, which means that a copy of the value of a variable is passed to a method and any modifications made within the method do not affect the original value of the variable. However, when objects are passed to a method, a copy of the object reference is passed, which means that both references (the original and the copy) point to the same real object in memory. Therefore, any changes made within the method will affect the actual object.</p><p>It is important to understand the difference between pass-by-value and pass-by-reference in Java to avoid confusion and errors in your code. In addition, it is critical to understand how objects are manipulated in Java and how modifications affect objects in different contexts.</p><p>In summary, although Java passes parameters by value, exceptions must be taken into account when passing objects to a method and making modifications to them. In general, it is important to have a good understanding of the behaviour of data in Java in order to write clear, concise and error-free code.</p><h4>I hope this post will help you to clarify all these concepts! 🧠</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc58d3b249a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>