<?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[Spring Boot Tips and Tricks - Medium]]></title>
        <description><![CDATA[Explore Spring Boot: From basics to advanced features, this series unveils how to efficiently build and deploy microservices. Dive into Spring ecosystem secrets! - Medium]]></description>
        <link>https://medium.com/spring-boot-tips-and-tricks?source=rss----77568777ac8c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Spring Boot Tips and Tricks - Medium</title>
            <link>https://medium.com/spring-boot-tips-and-tricks?source=rss----77568777ac8c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:38:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/spring-boot-tips-and-tricks" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring DI. Multiple Interface Implementations with Strategy Pattern]]></title>
            <link>https://medium.com/spring-boot-tips-and-tricks/spring-di-multiple-interface-implementations-with-strategy-pattern-eac54a029102?source=rss----77568777ac8c---4</link>
            <guid isPermaLink="false">https://medium.com/p/eac54a029102</guid>
            <category><![CDATA[strategy-pattern]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Paul Ravvich]]></dc:creator>
            <pubDate>Sat, 06 Apr 2024 07:53:40 GMT</pubDate>
            <atom:updated>2024-04-06T07:53:39.962Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One of the remarkable features of the Spring Framework is its ability to manage multiple implementations of the same interface, selecting the necessary implementation based on the execution context. Let’s see how this can be effectively applied in practice.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*5cNu86u4XHZAhxiCnOxt2Q.jpeg" /><figcaption>Spring: Multiple Interface Implementations with Strategy Pattern</figcaption></figure><p>Hi, this is Paul, and welcome to my Spring guide. Today we will discuss how Dependency Injection in the Spring Framework works for multiple implementations of one interface.</p><h4>Example: Data Conversion Service</h4><p>Imagine we have a service for converting data from one format to another, for example, from JSON to PDF or DOC formats. We implement this using the strategy pattern, where each strategy corresponds to a specific output format.</p><h4>Dependency Autowiring with @Component and @Autowired</h4><p>The Spring Framework offers a convenient way to manage dependencies through autowiring. For each conversion strategy, we define a separate component:</p><pre>public interface ReportConversionStrategy {<br>    byte[] convertReport(ReportDto report);<br>}<br><br>@Component(&quot;PDF&quot;)<br>public class PdfConversionStrategy implements ReportConversionStrategy {<br>    @Override<br>    public byte[] convertReport(ReportDto report) {<br>        return new byte[0];<br>    }<br>}<br><br>@Component(&quot;DOC&quot;)<br>public class DocConversionStrategy implements ReportConversionStrategy {<br>    @Override<br>    public byte[] convertReport(ReportDto report) {<br>        return new byte[0];<br>    }<br>}</pre><p>Using the @Autowired annotation, Spring automatically injects all available implementations of ReportConversionStrategy into our service, allowing us to dynamically select the necessary strategy based on input parameters.</p><h4>Implementation of the Conversion Service</h4><p>The conversion service integrates strategies and provides a universal interface for report conversion:</p><pre>@Service<br>public class ReportConversionService {<br><br>    private final Map&lt;String, ReportConversionStrategy&gt; strategies = new HashMap&lt;&gt;();<br><br>    @Autowired<br>    public ReportConversionService(List&lt;ReportConversionStrategy&gt; strategies) {<br>        strategies.forEach(strategy -&gt;<br>                this.strategies.put(strategy.getClass().getAnnotation(Component.class).value(), strategy));<br>    }<br><br>    public byte[] convertReport(String format, ReportDto report) {<br>        ReportConversionStrategy strategy = strategies.get(format.toUpperCase());<br>        if (strategy == null) {<br>            throw new UnsupportedOperationException(&quot;Unsupported format: &quot; + format);<br>        }<br>        return strategy.convertReport(report);<br>    }<br>}</pre><p>In this service, we use a map to link the format with the corresponding conversion strategy, allowing us to easily expand supported formats and implementations without altering the core logic of the service.</p><h4>Conclusion</h4><p>The application of the dependency autowiring mechanism in Spring, combined with the strategy pattern, demonstrates how to flexibly and efficiently manage different implementations of interfaces. This approach not only simplifies the addition of new features and code maintenance but also enhances its readability and improves the overall architecture of the application, making it more adaptive and extensible.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/PaulRavvich"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/in/pavel-ravvich/"><strong><em>LinkedIn</em></strong></a></li></ul><h4>Paul Ravvich</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac54a029102" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-boot-tips-and-tricks/spring-di-multiple-interface-implementations-with-strategy-pattern-eac54a029102">Spring DI. Multiple Interface Implementations with Strategy Pattern</a> was originally published in <a href="https://medium.com/spring-boot-tips-and-tricks">Spring Boot Tips and Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cache Regions: A Practical Guide]]></title>
            <link>https://medium.com/spring-boot-tips-and-tricks/spring-cache-regions-a-practical-guide-3325f0f8b213?source=rss----77568777ac8c---4</link>
            <guid isPermaLink="false">https://medium.com/p/3325f0f8b213</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[spring-cache]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Paul Ravvich]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 20:07:38 GMT</pubDate>
            <atom:updated>2024-02-13T20:07:38.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*VKfxNH8dfDxjEdsFafiJsg.png" /><figcaption>Spring Cache Regions</figcaption></figure><p>Hi, this is Paul, and welcome to the guide on using Cache Regions in SpringCache and Spring Framework.</p><h3>Introduction to Cache Regions</h3><p>Cache regions, essentially named areas within a cache, allow for the segregation of cached data. This segregation supports distinct cache configurations for different data types, enabling tailored cache eviction policies, expiration settings, and memory allocation. In the context of Spring, these regions are represented as separate caches, each with a unique name.</p><h3>Configuring Cache Regions in Spring</h3><p>Spring’s flexibility allows for straightforward cache region configuration. Here’s how to define multiple cache regions using ConcurrentMapCacheManager in a Spring application.</p><h4>Step 1: Define Cache Regions</h4><p>First, configure your cache manager bean in a configuration class annotated with @EnableCaching. This enables caching support in your Spring application.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.cache.CacheManager;<br>import org.springframework.cache.concurrent.ConcurrentMapCacheManager;<br><br>@Configuration<br>@EnableCaching<br>public class CacheConfig {<br><br>    @Bean<br>    public CacheManager cacheManager() {<br>        return new ConcurrentMapCacheManager(&quot;employees&quot;, &quot;departments&quot;);<br>    }<br>}</pre><p>In this example, we’ve created three distinct cache regions: employees anddepartments.</p><h4>Step 2: Utilize Cache Regions with Annotations</h4><p>Spring makes it easy to specify which cache region to use with the @Cacheable annotation. Simply annotate your service methods, indicating the appropriate cache name.</p><pre>import org.springframework.cache.annotation.Cacheable;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class EmployeeService {<br><br>    @Cacheable(cacheNames = &quot;employees&quot;)<br>    public Employee findEmployeeById(Long id) {<br>        // Logic to fetch employee by ID<br>        return new Employee();<br>    }<br>}<br><br>@Service<br>public class DepartmentService {<br><br>    @Cacheable(cacheNames = &quot;departments&quot;)<br>    public Department findDepartmentById(Long id) {<br>        // Logic to fetch department by ID<br>        return new Department();<br>    }<br>}</pre><p>This setup ensures that data fetched by these methods is stored in and retrieved from their respective cache regions.</p><h4>Step 3: Cache Eviction by Regions</h4><p>To maintain cache integrity and relevance, Spring offers the @CacheEvict annotation for invalidating cache data. This can be scoped to specific regions to clear relevant data as needed.</p><pre>import org.springframework.cache.annotation.CacheEvict;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class EmployeeService {<br><br>    @CacheEvict(cacheNames = &quot;employees&quot;, allEntries = true)<br>    public void clearEmployeeCache() {<br>        // Clears all entries in the employee cache region<br>    }<br>}</pre><p>This method, when called, will purge all cached data in the employees region, a useful operation after updating or deleting employee records to ensure cache coherence.</p><p>The allEntries parameter is designed to specify whether the cache eviction should affect just a single entry (associated with a specific key) or all entries within the specified cache region.</p><h3>Conclusion</h3><p>Using cache regions in Spring applications facilitates efficient data management and access patterns. By segmenting the cache, applications can achieve more granular control over caching behavior, optimizing performance and resource utilization. Whether you’re caching database queries, complex computations, or frequently accessed objects, leveraging cache regions can significantly contribute to your application’s scalability and user experience.</p><p>Remember, while caching can dramatically improve application performance, it’s essential to consider the consistency and timeliness of cached data, particularly in dynamic environments. Properly configured cache regions, alongside thoughtful eviction policies, can help maintain an effective balance between performance and data integrity.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/PaulRavvich"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/in/pavel-ravvich/"><strong><em>LinkedIn</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3325f0f8b213" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-boot-tips-and-tricks/spring-cache-regions-a-practical-guide-3325f0f8b213">Spring Cache Regions: A Practical Guide</a> was originally published in <a href="https://medium.com/spring-boot-tips-and-tricks">Spring Boot Tips and Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Proxies and CGLIB in Spring Framework]]></title>
            <link>https://medium.com/spring-boot-tips-and-tricks/dynamic-proxies-and-cglib-in-spring-framework-dcc4a9febdd5?source=rss----77568777ac8c---4</link>
            <guid isPermaLink="false">https://medium.com/p/dcc4a9febdd5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[dynamic-proxy]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[cglib]]></category>
            <dc:creator><![CDATA[Paul Ravvich]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 22:46:32 GMT</pubDate>
            <atom:updated>2024-02-09T22:47:30.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*VKfxNH8dfDxjEdsFafiJsg.png" /></figure><p>Hi, this is Paul, and welcome to my Spring guide. Today we will discuss how to Dynamic Proxies and CGLIB in Spring Framework work.</p><h3>Introduction</h3><p>In the Spring Framework, managing beans and their lifecycle is foundational for developing robust and flexible applications. Two powerful tools in Spring’s bean management arsenal are Dynamic Proxies and CGLIB (Code Generation Library). These tools allow for the extension of bean behavior without modifying the bean’s source code. This article explores the practical application of Dynamic Proxies and CGLIB in Spring, offering insights into how they can be utilized to create proxy objects for beans, thus seamlessly introducing additional behaviors like logging or transaction management.</p><h3>Advantages and Disadvantages</h3><h3>Dynamic Proxies</h3><p>Advantages:</p><ul><li>Java Standard: Dynamic Proxies are part of Java’s standard library, ensuring high compatibility and stability.</li><li>Performance: Since there’s no need to generate classes at runtime, Dynamic Proxies might offer better performance in some scenarios.</li><li>Ease of Use: Working with interfaces is facilitated by a straightforward and understandable API.</li></ul><p>Disadvantages:</p><ul><li>Interface Limitation: Dynamic Proxies can only proxy objects that implement an interface, limiting their application.</li></ul><h3>CGLIB</h3><p>Advantages:</p><ul><li>Flexibility: CGLIB can create proxies for classes that do not implement interfaces, making it a more versatile tool.</li><li>Inheritance: CGLIB allows for the proxying of classes by creating their subclasses, which can be beneficial in complex inheritance hierarchies.</li></ul><p>Disadvantages:</p><ul><li>Performance: Generating classes at runtime can negatively impact the application’s performance.</li><li>Complexity: Using CGLIB might be more complex due to the management of generated classes.</li></ul><h3>Why Dynamic Proxies Are Considered the Modern Standard</h3><p>Dynamic Proxies are regarded as the modern standard in dependency management and proxy creation in Java for several reasons:</p><ol><li>Interface Compatibility: Modern software architectures favor composition over inheritance. Using interfaces to define class contracts aligns with this trend.</li><li>Code Simplicity and Purity: Dynamic Proxies allow for the creation of proxies without modifying the class code, ensuring high modularity and testability.</li><li>Avoiding Issues with Final Classes: Since CGLIB creates subclasses of the proxied classes, it cannot work with final classes or methods. Dynamic Proxies do not encounter this issue as they operate at the interface level.</li></ol><h3>Choosing Between Dynamic Proxies and CGLIB</h3><p>The choice between Dynamic Proxies and CGLIB depends on the specific requirements of the application:</p><ul><li>Use Dynamic Proxies if your class implements interfaces and you value performance and Java compatibility.</li><li>Opt for CGLIB if you need to proxy classes without interfaces or when it’s necessary to control the behavior of specific class methods.</li></ul><h3>Conclusion</h3><p>Both Dynamic Proxies and CGLIB offer powerful capabilities for extending the functionality of beans in Spring. The choice between these approaches should be based on the architectural requirements of the application and the preferences and experience of the developer. It’s important to consider the advantages of each method and choose the one that best suits your needs.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/PaulRavvich"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/in/pavel-ravvich/"><strong><em>LinkedIn</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcc4a9febdd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-boot-tips-and-tricks/dynamic-proxies-and-cglib-in-spring-framework-dcc4a9febdd5">Dynamic Proxies and CGLIB in Spring Framework</a> was originally published in <a href="https://medium.com/spring-boot-tips-and-tricks">Spring Boot Tips and Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Circular Dependencies with @Lazy annotation]]></title>
            <link>https://medium.com/spring-boot-tips-and-tricks/resolving-circular-dependencies-in-spring-with-dynamic-proxies-and-lazy-annotation-a38c51f57fe9?source=rss----77568777ac8c---4</link>
            <guid isPermaLink="false">https://medium.com/p/a38c51f57fe9</guid>
            <category><![CDATA[circular-dependencies]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[cglib]]></category>
            <category><![CDATA[dynamic-proxy]]></category>
            <dc:creator><![CDATA[Paul Ravvich]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 22:04:17 GMT</pubDate>
            <atom:updated>2024-02-09T22:13:05.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*VKfxNH8dfDxjEdsFafiJsg.png" /><figcaption>Spring Circular Dependencies with @Lazy annotation</figcaption></figure><p>Hi, this is Paul, and welcome to my Spring guide. Today we will discuss how to resolve circular dependencies in Spring Boot.</p><h3>Understanding Circular Dependencies</h3><p>A circular dependency arises in a Spring application when two or more beans depend on each other, creating a loop that prevents the Spring container from determining the order of bean instantiation. This can lead to runtime errors and complications in the application’s startup process.</p><h3>Example With Interfaces</h3><h4>Step 1: Defining Interfaces</h4><p>First, we define two interfaces representing the interdependent services:</p><pre>public interface ServiceA {<br>    void methodInA();<br>}<br><br>public interface ServiceB {<br>    void methodInB();<br>}</pre><h4>Step 2: Implementing Interfaces</h4><p>Next, we implement these interfaces in our service classes and use setter injection with the @Lazy annotation to inject the dependencies. This approach allows Spring to manage the instantiation and dependency resolution.</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Lazy;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class ServiceAImpl implements ServiceA {<br><br>    private ServiceB serviceB;<br><br>    @Autowired<br>    public void setServiceB(@Lazy ServiceB serviceB) {<br>        this.serviceB = serviceB;<br>    }<br><br>    @Override<br>    public void methodInA() {<br>        System.out.println(&quot;Inside Method A&quot;);<br>    }<br>}<br><br>@Component<br>public class ServiceBImpl implements ServiceB {<br><br>    private ServiceA serviceA;<br><br>    @Autowired<br>    public void setServiceA(@Lazy ServiceA serviceA) {<br>        this.serviceA = serviceA;<br>    }<br><br>    @Override<br>    public void methodInB() {<br>        System.out.println(&quot;Inside Method B&quot;);<br>    }<br>}</pre><h4>Step 3: Configuring Spring Context</h4><p>Ensure your Spring context is configured to automatically scan for components and inject dependencies. This is typically achieved with @ComponentScan in your configuration class or through XML configuration.</p><h3>Example Without Interfaces</h3><p>Suppose we have two concrete service classes, ServiceAImpl and ServiceBImpl, without interfaces. By applying @Lazy alongside @Autowired for setter injection, Spring will use CGLIB to create a subclass proxy of these beans, facilitating lazy initialization and dependency resolution.</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Lazy;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class ServiceAImpl {<br><br>    private ServiceB serviceB;<br><br>    @Autowired<br>    public void setServiceB(@Lazy ServiceB serviceB) {<br>        this.serviceB = serviceB;<br>    }<br><br>    public void methodInA() {<br>        System.out.println(&quot;Inside Method A&quot;);<br>    }<br>}<br><br>@Component<br>public class ServiceBImpl {<br><br>    private ServiceA serviceA;<br><br>    @Autowired<br>    public void setServiceA(@Lazy ServiceA serviceA) {<br>        this.serviceA = serviceA;<br>    }<br><br>    public void methodInB() {<br>        System.out.println(&quot;Inside Method B&quot;);<br>    }<br>}</pre><p>(Note: The actual code snippet for the CGLIB example would mirror the earlier example but omit the interface implementation part, demonstrating Spring’s ability to handle circular dependencies with concrete classes.)</p><h3>Conclusion</h3><p>Spring’s support for interfaces and dynamic proxies provides a robust solution to the challenge of circular dependencies. By deferring bean instantiation until necessary, applications can maintain a clean architecture, avoid initialization errors, and ensure components are testable and loosely coupled. This technique exemplifies the flexibility and power of the Spring Framework in managing complex dependency scenarios.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/PaulRavvich"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/in/pavel-ravvich/"><strong><em>LinkedIn</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38c51f57fe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-boot-tips-and-tricks/resolving-circular-dependencies-in-spring-with-dynamic-proxies-and-lazy-annotation-a38c51f57fe9">Spring Circular Dependencies with @Lazy annotation</a> was originally published in <a href="https://medium.com/spring-boot-tips-and-tricks">Spring Boot Tips and Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Spring Framework.]]></title>
            <link>https://medium.com/spring-boot-tips-and-tricks/dependency-injection-in-spring-framework-ee73bd834c97?source=rss----77568777ac8c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ee73bd834c97</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Paul Ravvich]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 22:01:24 GMT</pubDate>
            <atom:updated>2024-02-09T22:50:09.676Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring DI. Lifecycle Bean Component and Context: Understanding the 4-Phase Constructor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8R5B_LRuli6JjogWugLV9Q.png" /><figcaption>Spring DI. Lifecycle Bean Component and Context: Understanding the 4-Phase Constructor</figcaption></figure><p>Hi, this is Paul, and welcome to my Spring guide. Today we will discuss how Dependency Injection in Spring Framework works.</p><h3>Introduction</h3><p>Hello, I’m Pavel Ravvich, and today we’ll dive into the fascinating world of the Spring Framework. One of Spring’s key features is Dependency Injection (DI), a mechanism that allows components to be more independent, testable, and modular. However, to use DI effectively, it is important to understand the bean lifecycle in Spring and the concept of the three-phase constructor.</p><h3>What is DI?</h3><p>DI is a process where one object provides dependencies to another object. In the context of Spring, this means that the framework creates and manages objects (beans) and their dependencies.</p><p>Life Cycle of Components in Spring<br>The life cycle of a bean in Spring can be divided into three main phases:</p><ol><li>Initialization: The bean is created and dependency injected.</li><li>Usage: The bean is ready to be used in the application.</li><li>Destruction: The bean is removed from the context.</li></ol><h3>Three Phase Constructor</h3><p>In Spring, a three-phase constructor refers to the calls that occur during bean initialization. These phases include:</p><ol><li><strong>postProcessBeforeInitialization</strong>: Executes immediately before the bean’s initialization method (for example, <strong>@PostConstruct</strong>).</li><li><strong>@PostConstruct</strong> (or other custom initialization methods): Spring calls this method after all required bean properties have been set.</li><li><strong>postProcessAfterInitialization</strong>: Executed immediately after the bean’s initialization method.</li></ol><h4>Example</h4><p>Let’s look at an example that demonstrates the use of these methods in a real Spring application.</p><pre>import jakarta.annotation.PostConstruct;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class Controller {<br><br>    private boolean isPrepared = false;<br>    private Configuration config;<br><br>    @PostConstruct<br>    public void init() {<br>        if (!isPrepared) {<br>            throw new IllegalStateException(&quot;Controller is not prepared&quot;);<br>        }<br>        config = new Configuration();<br>        System.out.println(&quot;Configuration loaded in @PostConstruct&quot;);<br>    }<br><br>    @GetMapping(&quot;/&quot;)<br>    public ResponseEntity&lt;String&gt; getData() {<br>        if (config == null) {<br>            throw new IllegalStateException(&quot;Configuration is not loaded&quot;);<br>        }<br>        return ResponseEntity.ok(&quot;Data from configured controller&quot;);<br>    }<br><br>    private static class Configuration {<br>        private final String property = &quot;value&quot;;<br>    }<br>}</pre><p>And <strong>BeanPostProcessor </strong>implementation for access to <strong>postProcessBeforeInitialization </strong>and <strong>postProcessAfterInitialization </strong>override</p><pre>import org.springframework.beans.BeansException;<br>import org.springframework.beans.factory.config.BeanPostProcessor;<br>import org.springframework.stereotype.Component;<br><br>import java.lang.reflect.Field;<br><br>@Component<br>public class ControllerBeanPostProcessor implements BeanPostProcessor {<br><br>    @Override<br>    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {<br>        if (bean instanceof Controller) {<br>            System.out.println(&quot;Preparing Controller in postProcessBeforeInitialization&quot;);<br>            try {<br>                Field field = bean.getClass().getDeclaredField(&quot;isPrepared&quot;);<br>                field.setAccessible(true);<br>                field.set(bean, true);<br>            } catch (NoSuchFieldException | IllegalAccessException e) {<br>                throw new RuntimeException(&quot;Failed to set field: isPrepared&quot;, e);<br>            }<br>        }<br>        return bean;<br>    }<br><br>    @Override<br>    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<br>        if (bean instanceof Controller) {<br>            System.out.println(&quot;Checking configuration in postProcessAfterInitialization for MyController&quot;);<br>            try {<br>                Field config = bean.getClass().getDeclaredField(&quot;config&quot;);<br>                config.setAccessible(true);<br>                return config.get(bean);<br>            } catch (NoSuchFieldException | IllegalAccessException e) {<br>                throw new RuntimeException(&quot;Failed to get field: config&quot;, e);<br>            }<br><br>        }<br>        return bean;<br>    }<br>}</pre><h3>Example Explanation</h3><h4>Controller initialization:</h4><ol><li>The controller contains two important fields: <strong>isPrepared </strong>and <strong>config</strong>. isPrepared serves as a flag indicating that the controller is ready for initialization. config is a configuration object.</li><li>At <strong>@PostConstruct</strong>(init), the controller checks whether it has been prepared (<strong>isPrepared</strong>). If not, initialization is aborted, preventing the configuration from loading incorrectly.</li></ol><p>This mechanism is critical for scenarios where loading the configuration must occur strictly after certain preconditions (for example, receiving data from an external source).</p><h4>BeanPostProcessor role:</h4><p>In <strong>postProcessBeforeInitialization</strong>, reflection is used to set <strong>isPrepared</strong>. This ensures that the prerequisites for <strong>@PostConstruct</strong> are satisfied.<br>In <strong>postProcessAfterInitialization</strong>, a check is made that the configuration has been loaded. This serves as a final check that the bean’s state is correct after it has been initialized.<br>This double-check before and after bean initialization ensures that the controller not only loads its configuration correctly but also that its state is as expected after initialization.</p><h3>Don’t Step On Rake</h3><pre>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br><br>@Service<br>public class MyService {<br><br>    @PostConstruct<br>    public void init() {<br>        transactionalMethod();<br>    }<br><br>    @Transactional<br>    public void transactionalMethod() {<br>        System.out.println(&quot;Transactional method executed&quot;);<br>    }<br>}</pre><p>When you try to call a method with the <strong>@Transactional</strong> annotation directly from an init method annotated with <strong>@PostConstruct</strong> in a Spring service, it will not work as expected for several reasons related to the way Spring manages transactions and the lifecycle of beans. Let’s look at why this won’t work step by step:</p><h4>Step 1: Initializing the Service</h4><p>When Spring creates a MyService bean, it first instantiates it and then initializes it, including calling methods annotated with <strong>@PostConstruct</strong>.</p><h4>Step 2: Call @PostConstruct</h4><p>The init method is called as part of the bean initialization process. This method makes a call to transactionalMethod.</p><h4>Step 3: Problem with Transactional Proxies</h4><p>Spring uses a proxy to manage transactions. When a method is annotated with <strong>@Transactional</strong>, the call to that method must go through a proxy so that Spring can manage the transaction (such as opening and closing transactions, handling exceptions, etc.).</p><p>However, when transactionalMethod is called directly from the init method, it is called on the <strong>MyService </strong>object itself, not on its proxy. At this time, the proxy that manages the transactions is not yet involved in call control. This means that transactional logic provided by Spring (such as creating a new transaction) will not be applied.</p><p>Step 4: No Transactional Processing<br>As a result, <strong>transactionalMethod </strong>is executed as a normal method without transactional processing. This means that any database or other transactional operations inside this method will not participate in a Spring-managed transaction.</p><h3>How to solve it? — Spring Events.</h3><h4>What Is Events in Spring</h4><p>Events in Spring are a way to implement the Observer design pattern that helps achieve loose coupling between components. Events provide asynchronous processing and allow components to respond to important changes in the application after the bean is completely adjusted and all proxies are created and transactional logic inside.</p><p>Example:</p><pre>@Service<br>public class MyService {<br><br>    @EventListener(condition = &quot;event.applicationContext.parent == null&quot;)<br>    public void init(ContextRefreshedEvent event) {<br>        transactionalMethod();<br>    }<br><br>    @Transactional<br>    public void transactionalMethod() {<br>        System.out.println(&quot;Transactional method executed&quot;);<br>    }<br>}</pre><h4>Why Check event.applicationContext.parent == null?</h4><p><strong>The event.applicationContext.parent == null</strong> check in @<strong>EventListener </strong>is done to filter out events that originate only from the root application context. This is important because different contexts (for example, root context and web context) can exist in Spring applications. When we only want to respond to events associated with the root context, this check ensures that our event handler does not respond to events from other contexts, which may be critical for certain business logic or initializations in the application.</p><h4>Other Useful Events in Spring</h4><p>Besides the <strong>ContextRefreshedEvent</strong>, there are many other useful events in Spring:</p><ol><li><strong>ContextStartedEvent</strong>: Event raised when the <strong>ApplicationContext </strong>is started using the <strong>start()</strong> method.</li><li><strong>ContextStoppedEvent</strong>: Event generated when the ApplicationContext is stopped using the <strong>stop()</strong> method.</li><li><strong>ContextClosedEvent</strong>: Event published when the ApplicationContext is closed.</li><li><strong>RequestHandledEvent</strong>: Event associated with the completion of processing an HTTP request.</li><li><strong>Custom Events</strong>: You can also create your custom events for the specific needs of your application.</li></ol><h3>Conclusion</h3><p>Understanding the life cycle of beans and DI in Spring not only helps you write clean and efficient code but also provides a deep understanding of how the framework works. This overview and example will help you understand these concepts better.</p><p>See you in the next part of the guide!</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/PaulRavvich"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/in/pavel-ravvich/"><strong><em>LinkedIn</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee73bd834c97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spring-boot-tips-and-tricks/dependency-injection-in-spring-framework-ee73bd834c97">Dependency Injection in Spring Framework.</a> was originally published in <a href="https://medium.com/spring-boot-tips-and-tricks">Spring Boot Tips and Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>