<?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 Sathira Basnayake on Medium]]></title>
        <description><![CDATA[Stories by Sathira Basnayake on Medium]]></description>
        <link>https://medium.com/@sathira97?source=rss-25621e89f432------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6lkh2DgAElcRRKswNqtNbw.jpeg</url>
            <title>Stories by Sathira Basnayake on Medium</title>
            <link>https://medium.com/@sathira97?source=rss-25621e89f432------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:01:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sathira97/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[Understanding Spring Framework: Part 5]]></title>
            <link>https://medium.com/@sathira97/understanding-spring-framework-part-5-c3dd646a0c4a?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3dd646a0c4a</guid>
            <category><![CDATA[spring-training]]></category>
            <category><![CDATA[spring-internals]]></category>
            <category><![CDATA[spring-interview]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 05:56:20 GMT</pubDate>
            <atom:updated>2026-03-07T06:38:55.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Post-Instantiation Bean Lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ln9FChnfyl88EnNulXLCA.png" /></figure><p>In the <a href="https://medium.com/@sathira97/understanding-spring-framework-part-4-a88878241fa1">previous part</a>, we saw how Spring creates a bean from a BeanDefinition. The container resolves constructor dependencies, creates the object using reflection, and injects any remaining dependencies.</p><p>In our earlier explanation, we treated the <em>initialization phase</em> as a single step in the bean creation process. In reality, however, several important things happen during this stage inside the container.</p><p>Even after the bean is created and its dependencies are injected, Spring still performs a number of lifecycle operations before the bean is considered fully ready to use.</p><p>In this part, we will open that initialization phase and explore what really happens after a bean is created.</p><h3>The Initialization Phase in the Bean Lifecycle</h3><p>When Spring creates a bean, the process does not end immediately after the constructor runs and dependencies are injected.</p><p>After dependency injection, the container enters a stage known as the <strong>initialization phase</strong>. During this phase, Spring performs several lifecycle operations that prepare the bean for use inside the application.</p><p>These operations allow both the container and external extensions to interact with the bean before it becomes fully available. For example, Spring may invoke special callback interfaces, run initialization methods, or allow framework components to inspect and modify the bean.</p><p>In simplified terms, the initialization phase includes the following steps:</p><ul><li>Aware callbacks</li><li>BeanPostProcessor.beforeInitialization</li><li><a href="http://twitter.com/PostConstruct">@PostConstruct</a></li><li>afterPropertiesSet()</li><li>custom init-method</li><li>BeanPostProcessor.afterInitialization</li></ul><p>Only after these steps are completed does Spring consider the bean fully initialized and ready to be used by the application.</p><h3>Aware Interfaces in the Bean Lifecycle</h3><p>One of the first steps in the initialization phase is the invocation of <strong>Aware callbacks</strong>.</p><p>Spring provides a set of special interfaces that allow a bean to receive information about the container that created it. These are known as <strong>Aware interfaces</strong>.</p><p>If a bean implements one of these interfaces, the container will automatically invoke the corresponding method during initialization.</p><p>For example, the BeanNameAware interface allows a bean to learn the name assigned to it in the container:</p><pre>public class ExampleService implements BeanNameAware {<br><br>    @Override<br>    public void setBeanName(String name) {<br>        System.out.println(&quot;Bean name is: &quot; + name);<br>    }<br>}</pre><p>When Spring initializes this bean, it calls setBeanName() and passes the bean’s name as defined in the container.</p><p>Spring provides several Aware interfaces for accessing different types of container information, such as:</p><ul><li>BeanNameAware</li><li>BeanFactoryAware</li><li>ApplicationContextAware</li><li>EnvironmentAware</li></ul><p>These callbacks allow beans to interact with the container infrastructure when necessary.</p><p>In the bean lifecycle, these callbacks are invoked after dependency injection but before the main initialization callbacks such as @PostConstruct or afterPropertiesSet().</p><p>After understanding Aware callbacks, we can now look at another important mechanism in the lifecycle: the <strong>BeanPostProcessor</strong>.</p><h3>What a BeanPostProcessor Actually Is</h3><p>A <strong>BeanPostProcessor</strong> is a special type of Spring bean whose job is to intercept and modify other beans during their lifecycle.</p><p>Think of it as a <strong>hook mechanism</strong> built into the container.</p><p>Instead of Spring hard-coding every feature into the container itself, it allows additional components to plug into the lifecycle.</p><p>Those plug-ins are <strong>BeanPostProcessors</strong>.</p><h3>Why Spring Uses This Mechanism</h3><p>This design allows Spring to be <strong>extensible</strong>.</p><p>Instead of baking features directly into the container, Spring implements many features as BeanPostProcessors.</p><p>This means the container can stay simple while features are added as extensions. Many important Spring features work this way.<br>eg: <a href="http://twitter.com/Autowired">@Autowired</a>, <a href="http://twitter.com/Value">@Value</a>, <a href="http://twitter.com/PostConstruct">@PostConstruct</a>, <a href="http://twitter.com/Transactional">@Transactional</a>, AOP proxies</p><p>A BeanPostProcessor can perform three main actions:</p><ul><li>Inspect the bean</li><li>Modify the bean</li><li>Replace the bean with another object</li></ul><h3>When BeanPostProcessors Are Invoked</h3><p>Once a bean has been created and its dependencies have been injected, Spring begins the initialization phase. During this stage, the container gives registered <strong>BeanPostProcessors</strong> an opportunity to interact with the bean.</p><p>Every bean that is created by the container passes through all registered BeanPostProcessors. Spring calls two methods on each processor during the lifecycle:</p><ul><li>postProcessBeforeInitialization()</li><li>postProcessAfterInitialization()</li></ul><p>These methods are invoked at specific points in the initialization phase.</p><p>First, Spring calls postProcessBeforeInitialization() on each BeanPostProcessor. This happens before any initialization callbacks such as @PostConstruct, afterPropertiesSet(), or custom init methods are executed.</p><p>After the initialization callbacks are completed, Spring calls postProcessAfterInitialization() on each BeanPostProcessor.</p><p>Because every bean passes through these processors, they provide a powerful extension point for the container. Framework features can inspect beans, apply additional behavior, or even replace the bean instance before it is returned to the application.</p><p>Now let’s examine these phases in the order they occur.</p><blockquote>In most applications, developers rarely need to implement their own <em>BeanPostProcessor</em>. Many important processors are already provided by the Spring framework to support features such as dependency injection, annotation processing, and AOP. However, the mechanism remains available for developers or library authors who need to extend the container’s behavior.</blockquote><h3>BeanPostProcessor.beforeInitialization</h3><p>After Aware callbacks have been executed, Spring begins invoking the first lifecycle hook provided by BeanPostProcessor.</p><p>At this stage, the container calls the postProcessBeforeInitialization() method on <strong>every registered BeanPostProcessor</strong>.</p><p>This method is invoked <strong>before any initialization callbacks</strong> such as @PostConstruct, afterPropertiesSet(), or custom init methods.</p><p>Because every bean passes through this stage, BeanPostProcessors have the opportunity to inspect or modify the bean before initialization logic runs.</p><p>Many internal Spring components use this mechanism. For example, the processor responsible for handling @PostConstruct annotations scans the bean during this phase to identify initialization methods that need to be invoked.</p><p>This hook provides a powerful extension point that allows framework features and third-party libraries to participate in the bean lifecycle.</p><h3>Initialization Callbacks</h3><p>Once BeanPostProcessor.beforeInitialization() has been executed, Spring moves to the next stage of the lifecycle: <strong>initialization callbacks</strong>.</p><p>Initialization callbacks allow a bean to run custom logic after all dependencies have been injected but before the bean becomes fully available to the application.</p><p>Spring provides three mechanisms for defining initialization logic.</p><h4>@PostConstruct</h4><p>The most commonly used approach is the @PostConstruct annotation.</p><pre>@PostConstruct<br>public void init() {<br>    System.out.println(&quot;Bean initialization logic&quot;);<br>}</pre><p>Spring invokes this method after dependency injection is completed. It is typically used to perform setup tasks that depend on injected dependencies.</p><p>Although @PostConstruct appears as a separate step in the lifecycle, it is actually invoked by a BeanPostProcessor called CommonAnnotationBeanPostProcessor.</p><p>During the postProcessBeforeInitialization() phase, this processor scans the bean for methods annotated with @PostConstruct and invokes them.</p><p>This shows an important design principle in Spring: many features are not hard-coded into the container itself. Instead, they are implemented through extension points like BeanPostProcessor.</p><h4>InitializingBean.afterPropertiesSet()</h4><p>Spring also provides the InitializingBean interface.</p><pre>public class UserService implements InitializingBean {<br>@Override<br>    public void afterPropertiesSet() {<br>        System.out.println(&quot;Initialization logic&quot;);<br>    }<br>}</pre><p>If a bean implements this interface, Spring will call the afterPropertiesSet() method during initialization.</p><h4>Custom init method</h4><p>Finally, initialization logic can also be configured externally using a custom init method.</p><pre>@Bean(initMethod = &quot;init&quot;)<br>public UserService userService() {<br>    return new UserService();<br>}</pre><p>This approach is useful when the class itself cannot be modified, such as when using third-party libraries.</p><p>Spring executes these initialization mechanisms in the following order:</p><ul><li><a href="http://twitter.com/PostConstruct">@PostConstruct</a></li><li>afterPropertiesSet()</li><li>custom init-method</li></ul><p>After these callbacks are completed, the initialization phase continues with BeanPostProcessor.afterInitialization().</p><h3>BeanPostProcessor.afterInitialization</h3><p>After initialization callbacks have been executed, Spring invokes the second lifecycle hook provided by BeanPostProcessor.</p><p>At this stage, the container calls the postProcessAfterInitialization() method on every registered BeanPostProcessor.</p><pre>postProcessAfterInitialization(Object bean, String beanName)</pre><p>Just like the earlier hook, this method is invoked for every bean created by the container.</p><p>However, this stage is particularly important because a BeanPostProcessor can return a <strong>different object instead of the original bean</strong>.</p><p>This capability allows the container to enhance beans with additional behavior. In many cases, the processor wraps the original bean inside a <strong>proxy object</strong> that intercepts method calls.</p><p>This mechanism is used to implement several powerful Spring features, including:</p><ul><li>transaction management (@Transactional)</li><li>asynchronous execution (@Async)</li><li>caching (@Cacheable)</li><li>AOP advice</li></ul><p>For example, when a bean is annotated with @Transactional, Spring may replace the original bean with a proxy that manages transaction boundaries around method calls.</p><p>Because this happens during postProcessAfterInitialization(), the object returned from the container may not be the same instance that was originally created by the constructor.</p><p>After this step is completed, the bean is considered fully initialized and ready for use by the application.</p><blockquote>Because proxy wrapping happens during BeanPostProcessor.afterInitialization(), the object returned from the container may not be the original instance created by the constructor. Instead, it may be a proxy that intercepts method calls to provide additional behavior such as transactions or AOP.</blockquote><h3>The Complete Bean Initialization Lifecycle</h3><p>At this point, we have explored the different mechanisms that operate during the initialization phase of a Spring bean. To better understand how these pieces fit together, it helps to look at the entire lifecycle in sequence.</p><p>When the Spring container creates and prepares a bean, the following steps occur:</p><pre>1. Bean instance is created (constructor)<br>2. Dependencies are injected<br>3. Aware callbacks are invoked<br>4. BeanPostProcessor.beforeInitialization()<br>5. @PostConstruct<br>6. afterPropertiesSet()<br>7. custom init-method<br>8. BeanPostProcessor.afterInitialization()<br>9. Bean is ready for use</pre><p>Each stage plays a specific role in preparing the bean.</p><p>When all these steps are completed, the bean is considered <strong>fully initialized</strong>. If the bean has singleton scope, the container stores it in the singleton cache, and all future requests for that bean return the same instance.</p><p>Understanding this lifecycle helps reveal how the Spring container manages and enhances objects behind the scenes. Many of the framework’s powerful features rely on these lifecycle stages to interact with beans as they are created and prepared for use.</p><p>While this lifecycle describes how Spring creates and prepares a bean, the container may manage beans differently depending on their <strong>scope</strong>. So far, we have implicitly assumed that the bean is a singleton — meaning only one instance exists in the container.</p><p>However, Spring supports several scopes that change how beans are created, stored, and reused inside the container.</p><p>In the next part, we will explore <strong>bean scopes</strong> and see how the container adapts its behavior when beans are defined as prototype, request, or other scopes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3dd646a0c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Framework: Part 4]]></title>
            <link>https://medium.com/@sathira97/understanding-spring-framework-part-4-a88878241fa1?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88878241fa1</guid>
            <category><![CDATA[spring-internals]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 10:08:58 GMT</pubDate>
            <atom:updated>2026-03-07T06:47:02.540Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>From BeanDefinition to Bean Instance: Inside the Instantiation Pipeline</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ln9FChnfyl88EnNulXLCA.png" /></figure><p>In <a href="https://medium.com/@sathira97/understanding-spring-framework-part-3-b0c46cf01782?postPublishedType=repub">Part 3</a>, we examined what BeanDefinitions are and how Spring creates them from annotations and configuration metadata. We established that BeanDefinitions are not actual objects, but structured blueprints describing how a bean should be created and managed inside the container.</p><p>Spring must now transform these definitions into real, dependency-injected, fully initialized objects. This transformation occurs during the instantiation phase of the ApplicationContext lifecycle, specifically inside the refresh() process.</p><p>In this article, we will look into how the bean Definitions turn into managed bean instances ready for use in the application.</p><h3>How Bean Creation Starts</h3><p>By the time Spring reaches this stage in the refresh() lifecycle, several important steps have already completed. BeanDefinitions have been created and processed, BeanFactoryPostProcessors have finished their work, and BeanPostProcessors have been registered. The container is now ready to move into the instantiation phase.</p><p>During this phase, Spring begins creating non-lazy singleton beans. Internally, it iterates over all registered BeanDefinitions and, for each bean that is a singleton and not marked as lazy, it triggers creation by calling:<br>getBean(beanName)</p><p>This is a crucial detail.</p><p>Spring does not directly invoke constructors at this stage. Instead, bean creation begins through getBean() the same method used to retrieve beans at runtime. In other words, even during startup, Spring uses its standard retrieval mechanism to initiate bean creation.</p><p>The getBean() method plays a dual role:</p><ul><li>If the bean already exists in the singleton cache, it simply returns the existing instance.</li><li>If the bean does not yet exist, it initiates the creation process, stores the fully initialized bean in the singleton cache, and then returns it.</li></ul><p>This design ensures consistent behavior between startup-time instantiation and runtime retrieval. Once a singleton bean is fully created and initialized, it is stored in an internal cache and reused for all subsequent requests.</p><p>So even during application startup, bean instantiation begins with a simple but powerful call: getBean().</p><h3>Following One Bean Through the Instantiation Pipeline</h3><p>To understand how Spring turns a BeanDefinition into a real object, let’s follow what happens when the container creates a single bean.</p><p>When Spring enters the instantiation phase, it begins by calling getBean() for each non-lazy singleton. This method acts as the entry point for bean creation.</p><p>The first thing Spring does is check whether the bean already exists in the singleton cache. If the bean has already been created, the existing instance is returned immediately. If not, the container proceeds with creation.</p><p>Next, Spring determines which constructor should be used. It inspects the class and selects a constructor that it can fully satisfy. If the constructor requires other beans as parameters, Spring resolves those dependencies by retrieving or creating them first.</p><p>Once all constructor dependencies are available, Spring invokes the constructor using reflection. At this moment, a raw object instance is created.</p><p>After construction, Spring performs dependency injection for any remaining properties, such as field or setter-based dependencies.</p><p>Then, the bean goes through the initialization phase. During this stage, Spring applies registered post-processors and executes any initialization callbacks.</p><p>Finally, once the bean is fully initialized, it is stored in the singleton cache. From this point onward, every request for that bean will return the same managed instance.</p><p>Let’s summarize the complete process in a structured way.</p><p>When Spring creates a singleton bean during the refresh() phase, the following steps occur:</p><ol><li><strong>getBean(beanName) is called</strong><br> Bean creation begins through the standard retrieval mechanism.</li><li><strong>Singleton cache is checked</strong><br> If the bean already exists, the existing instance is returned.<br> If not, Spring proceeds with creation.</li><li><strong>Constructor is selected</strong><br> Spring inspects the class and determines which constructor it can fully satisfy.</li><li><strong>Constructor dependencies are resolved</strong><br> For each constructor parameter, Spring retrieves or creates the required dependency.</li><li><strong>The bean instance is created</strong><br> The selected constructor is invoked using reflection, creating a raw object instance.</li><li><strong>Property-based dependencies are injected (if any)</strong><br> Field or setter-based injections are performed.</li><li><strong>Initialization phase runs</strong><br> Spring applies registered post-processors and executes any initialization callbacks.</li><li><strong>The fully initialized bean is stored in the singleton cache</strong><br> From this point onward, all future requests for this bean return the same instance.</li></ol><p>This sequence transforms a simple BeanDefinition blueprint into a fully managed object inside the container.</p><h3>Observing the Instantiation Process: A Simple Experiment</h3><p>Let’s confirm this lifecycle with a small experiment. We’ll define three beans with a clear dependency chain — OrderService depends on PaymentService, which in turn depends on PaymentGateway.</p><pre>@Service<br>public class PaymentGateway {<br><br>    public PaymentGateway() {<br>        System.out.println(&quot;[1] PaymentGateway instantiated (no dependencies)&quot;);<br>    }<br>}</pre><pre>@Service<br>public class PaymentService {<br><br>    private final PaymentGateway paymentGateway;<br><br>    public PaymentService(PaymentGateway paymentGateway) {<br>        System.out.println(&quot;[2] PaymentService instantiated (depends on PaymentGateway)&quot;);<br>        this.paymentGateway = paymentGateway;<br>    }<br>}</pre><pre>@Service<br>public class OrderService {<br><br>    private final PaymentService paymentService;<br><br>    public OrderService(PaymentService paymentService) {<br>        System.out.println(&quot;[3] OrderService instantiated (depends on PaymentService)&quot;);<br>        this.paymentService = paymentService;<br>    }<br>}<br>```<br><br>When the application starts, the console output will always be:<br>```<br>[1] PaymentGateway instantiated (no dependencies)<br>[2] PaymentService instantiated (depends on PaymentGateway)<br>[3] OrderService instantiated (depends on PaymentService)</pre><h3>What Does This Show?</h3><p>The important observation here is that the instantiation order is not determined by classpath scanning or bean registration order. It is driven entirely by the dependency graph.</p><p>We have a chain: OrderService → PaymentService → PaymentGateway. The BeanDefinition registry internally uses a LinkedHashMap, so the iteration order depends on how the component scanner discovers these classes which is something influenced by classpath ordering and package structure, not by the developer. Yet the output is always the same. Here&#39;s why.</p><p>If the container encounters OrderService first during its iteration, it detects a constructor dependency on PaymentService and internally calls getBean(&quot;paymentService&quot;). That call, in turn, detects a dependency on PaymentGateway and triggers getBean(&quot;paymentGateway&quot;). Since PaymentGateway has no dependencies, it is created immediately. The call stack then unwinds, completing creation from the innermost dependency outward. Then PaymentService is constructed next with the now-available PaymentGateway, and finally OrderService is constructed with the now-available PaymentService. The chain resolves from the leaf upward.</p><p>It is also important to understand what happens after the constructors run. Instantiation is not the final step. Each bean still goes through the remaining initialization stages of the container lifecycle. During this phase, Spring applies registered post-processors and executes any defined initialization callbacks.</p><p>Only after this full initialization sequence is complete does Spring place the fully initialized bean into its internal singleton cache. From that point onward, any call to getBean() for that bean will return the same cached instance, without invoking the constructor again.</p><p>This experiment confirms the core principle:</p><blockquote>Spring does not rely on registration order to determine when a bean is created. The dependency graph determines when a bean can be safely constructed, and the container resolves it recursively, constructing each bean only when all of its dependencies are fully available.</blockquote><h3>Beyond Instantiation</h3><p>At this point, the bean has been constructed, its dependencies injected, and if it is a singleton stored in the container’s cache.</p><p>But is it truly finished?</p><p>Not quite.</p><p>Between object creation and becoming a fully usable component, Spring performs several additional steps. It invokes initialization callbacks, applies post-processors, and may even wrap the bean in a proxy to provide features like transactions or asynchronous execution.</p><p>In the <a href="https://medium.com/@sathira97/understanding-spring-framework-part-5-c3dd646a0c4a">next part</a>, we will explore the full bean lifecycle after instantiation including BeanPostProcessor, initialization hooks, and how Spring enhances beans behind the scenes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88878241fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docusaurus Under the Hood: Part 1]]></title>
            <link>https://medium.com/@sathira97/docusaurus-under-the-hood-part-1-44bd1bb9ba78?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/44bd1bb9ba78</guid>
            <category><![CDATA[technical-documentation]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[docusaurus]]></category>
            <category><![CDATA[technical-writing]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 04:43:54 GMT</pubDate>
            <atom:updated>2026-02-26T04:46:58.169Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Mental Model of a Documentation Compiler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1QPLx_i4I3SgmvApOautw.png" /></figure><p>In the <a href="https://medium.com/@sathira97/what-is-docusaurus-49e6a33dad7d">previous article</a>, we discussed what Docusaurus is and when we should use it. In this article, we will move beyond features and configuration. Instead, we will build a mental model of how Docusaurus actually works underneath.</p><p>To understand Docusaurus properly, you must stop thinking of it as <br>“a documentation website generator.”</p><p>Instead, think of it as:</p><blockquote><em>A documentation compiler.</em></blockquote><p>Just like a programming language compiler transforms source code into an executable program, Docusaurus transforms documentation content into a structured, interactive website.</p><h3>The High-Level Pipeline</h3><p>At an abstract level, Docusaurus operates in four stages:</p><ol><li>Content Ingestion</li><li>Content Structuring</li><li>Compilation</li><li>Static Rendering</li></ol><p>Let’s understand each stage conceptually.</p><h3>Content Ingestion</h3><p>Everything begins with plain files inside your repository.</p><p>These files contain:</p><ul><li>Text</li><li>Headings</li><li>Links</li><li>Metadata</li><li>Sometimes embedded components</li></ul><p>At this stage, Docusaurus is simply reading structured content from the file system.</p><p>This is important:</p><p>The documentation is not stored in a database.<br> It is not stored in an external platform.<br> It lives alongside your source code.</p><p>That is the foundation of the Docs-as-Code philosophy.</p><h3>Content Structuring — Turning Text into Meaning</h3><p>Raw text alone is not enough to build a documentation site.</p><p>The system must understand:</p><ul><li>What is a page?</li><li>What is a section?</li><li>What belongs in the sidebar?</li><li>What version does this file belong to?</li><li>How should URLs be generated?</li></ul><p>This is the stage where Docusaurus transforms content into structured information.</p><p>Think of it like organizing books in a library:</p><ul><li>Some books belong to the “Beginner” section.</li><li>Some belong to “Advanced.”</li><li>Some belong to version 1.0.</li><li>Others belong to version 2.0.</li></ul><p>This stage is where structure emerges.</p><p>The result is no longer “just text.”<br> It becomes a structured representation of your documentation system.</p><h3>Compilation — Turning Structure into Application Code</h3><p>Once the content is structured, it must be converted into something the browser can understand.</p><p>At this stage, Docusaurus transforms documentation into React components.</p><p>This is what makes Docusaurus different from older documentation generators.</p><p>Instead of producing static HTML directly, it produces an application — a React-based site — where:</p><ul><li>Pages are pre-rendered</li><li>Navigation is dynamic</li><li>Interactive components are supported</li><li>Client-side transitions are smooth</li></ul><p>So the documentation becomes not just content, but part of a frontend application.</p><p>This step happens during the build process.</p><p>There is no runtime server involved.</p><h3>Static Rendering — Producing the Final Site</h3><p>In the final stage, Docusaurus generates:</p><ul><li>Static HTML files (for fast initial loading and SEO)</li><li>A JavaScript bundle (for client-side interactivity)</li></ul><p>The output is a folder that can be deployed to any static hosting service.</p><p>At runtime, there is no backend logic generating pages. Everything has already been compiled.</p><p>The site behaves like an application, but it is delivered like a static website.</p><h3>The Core Mental Shift</h3><p>Most people think Docusaurus is:</p><blockquote><em>Markdown → HTML</em></blockquote><p>That is not accurate.</p><p>A better mental model is:</p><blockquote><em>Documentation Source → Structured Data → React Application → Static Site</em></blockquote><p>It behaves much closer to a compiler than a template engine.</p><h3>Why This Architecture Matters</h3><p>This architecture enables several important properties:</p><ul><li>Versioned documentation</li><li>Automatic sidebar generation</li><li>Structured routing</li><li>Interactive components inside docs</li><li>Clean integration with CI/CD</li></ul><p>All of these features emerge from the pipeline design.</p><p>They are not random features.<br> They are consequences of the architecture.</p><h3>The Bigger Picture</h3><p>When you understand Docusaurus at this level, you start seeing it differently.</p><p>It is not just “a tool to build docs.”</p><p>It is a system that:</p><ul><li>Treats documentation as source code</li><li>Applies transformation stages</li><li>Compiles it into a structured web application</li><li>Outputs a statically deployable artifact</li></ul><p>That is why it fits naturally into engineering workflows.</p><h3>Conclusion</h3><p>In this article, we built a high-level mental model of Docusaurus as a documentation compiler. We intentionally stayed away from themes, styling, and configuration details. Those are important for usage, but they do not explain the core architectural idea.</p><p>What truly makes Docusaurus interesting is the transformation pipeline that happens during the build process.</p><p>A simple Markdown file does not become HTML directly. It goes through multiple transformation stages. It is parsed, structured, enriched, compiled into React components, and finally rendered into static output. This pipeline is where the real engineering design lives.</p><p>In the next article. We will examine the internal processing flow . We will trace the path step by step and understand how documentation becomes an application before it becomes a website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44bd1bb9ba78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Docusaurus]]></title>
            <link>https://medium.com/@sathira97/what-is-docusaurus-49e6a33dad7d?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/49e6a33dad7d</guid>
            <category><![CDATA[technical-documentation]]></category>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[docs-as-code]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[docusaurus]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 04:47:31 GMT</pubDate>
            <atom:updated>2026-02-25T04:48:15.357Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Understanding Docusaurus: When to Use It and Why It Exists</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1QPLx_i4I3SgmvApOautw.png" /></figure><p>In this article, we will look at what Docusaurus is and when we should use it.</p><p>Docusaurus is a static site generator (SSG) specifically designed for building documentation websites with minimal setup and strong developer ergonomics. It is based on React and maintained by Meta. It is optimized for technical documentation, blogs, and project sites.</p><h3>So why does Docusaurus exist?</h3><p>At first glance, it may not seem necessary. We already have static site generators like Jekyll and Hugo, and modern frameworks like Next.js can be used to build almost any kind of website.</p><p>But technical documentation is not just another website.</p><p>When building documentation for a real software project, certain requirements appear quickly: versioning across releases, structured and hierarchical sidebars, stable internal linking, proper search, and long-term maintainability. With a general-purpose framework, you can implement all of this but you will end up building the infrastructure yourself.</p><p>Docusaurus exists to solve this recurring engineering problem. It treats documentation as a first-class concern and provides these structural patterns out of the box.</p><p>On the other side are enterprise platforms like Confluence. They prioritize collaboration and ease of editing, abstracting away the infrastructure entirely. While convenient, this approach disconnects documentation from the codebase. Content lives inside a platform, versioning is page-based rather than release-based, and integration with engineering workflows becomes limited.</p><p>For engineering teams, documentation is part of the software lifecycle. Docusaurus keeps it inside the repository, allowing it to evolve alongside the code through pull requests, version tags, and automated deployments.</p><h3><strong>The Docs-as-Code Philosophy</strong></h3><p>The <strong>Docs-as-Code</strong> philosophy treats documentation the same way we treat source code. Instead of writing documentation inside a separate platform, it lives inside the repository, follows the same workflow, and evolves alongside the application.</p><p>So whats special about docusaurus is it allows developers to adopt this Docs-as-Code without building infrastructure from scratch.</p><h3>When Should We Use Docusaurus?</h3><p>Docusaurus is not necessary for every project. If you are building a simple landing page or a small blog, a general-purpose framework or hosted platform may be more than enough.</p><p>Docusaurus becomes valuable when documentation itself becomes a structured system rather than a collection of pages.</p><p>You should consider using Docusaurus when:</p><ul><li>Your project has multiple versions</li><li>Documentation needs deep structure</li><li>You follow a Docs-as-Code workflow</li><li>You are building public developer documentation</li><li>You want long-term maintainability without heavy frontend engineering</li></ul><h3>When You Should Not Use It</h3><p>You probably do not need Docusaurus if:</p><ul><li>Documentation is internal and collaborative-only (Something like conflunce is sufficient).</li><li>The project is small and unlikely to grow.</li><li>You need a highly customized marketing site rather than structured docs.</li><li>Non-technical writers must edit content without Git workflows.</li></ul><h3>Conclusion</h3><p>So as you can see Docusaurus is a platform which caters a specific kind of requirements and it is not for everybody. Now you can choose whether you want to use Docusaurus or not based on your requirements.</p><p>There are already many step-by-step tutorials explaining how to set up a Docusaurus site, so this article did not focus on installation or configuration.</p><p>Instead, the next article will go deeper. We will move beyond <em>what</em> Docusaurus is and examine <em>how it works underneath</em> — how it processes content, generates routes, builds static assets, and uses React in its rendering pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49e6a33dad7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Framework: Part 3]]></title>
            <link>https://medium.com/@sathira97/understanding-spring-framework-part-3-b0c46cf01782?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c46cf01782</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[spring-internals]]></category>
            <category><![CDATA[beandefinition]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 01:47:01 GMT</pubDate>
            <atom:updated>2026-03-02T10:14:36.671Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Metadata to BeanDefinition: How Spring Registers Application Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmD6FVxuakeU00Pi-AMAtw.png" /></figure><p>In <a href="https://medium.com/@sathira97/understanding-spring-framework-part-2-e205ada1356e">Part 2</a>, we explored the Spring IoC container and its main implementations such as BeanFactory and ApplicationContext. We understood that the container is responsible for managing application objects, their dependencies, and their lifecycle.</p><p>The next question we have is</p><p><em>How do these objects get into the container in the first place?</em></p><p>Before any bean is instantiated, the container must first understand <strong>what to create, how to create it, and how it should behave</strong>. This information is captured internally using a concept called the <strong>BeanDefinition</strong>.</p><p>In this article, we will try to understand how Spring transforms configuration metadata into BeanDefinition objects, registers them inside the container, and prepares them for instantiation during the refresh() process.</p><h3>The Concept of BeanDefinition</h3><p>BeanDefinition is not the bean itself but it is a internal representation of the bean in container which contains structured piece of metadata about the bean. This contains</p><ul><li>The bean class to instantiate</li><li>The scope (singleton, prototype, etc.)</li><li>Constructor arguments and property values</li><li>Factory methods (if applicable)</li><li>Initialization and destruction methods</li><li>Lazy loading flags</li><li>Autowire rules</li><li>Qualifiers and primary markers</li></ul><p>In Spring there are several ways to configure a bean and what the spring container does is it reads these configurations and create the beanDefinitions beforehand.</p><p>After that the spring container works with these bean definitions so spring can work with different configuration methods simultaneously.</p><p>Crucial details to keep in mind:</p><blockquote><em>Spring first builds a graph of BeanDefinitions. Only after that does it instantiate actual objects.</em></blockquote><h3>From Annotations to BeanDefinitions — Conceptual Pipeline</h3><p>In the previous section we observed that the container holds BeanDefinition objects before any actual beans are created.<br> This raises an important question:</p><p><strong>How does Spring transform annotations like </strong><strong>@Service or </strong><strong>@Component into these internal BeanDefinition representations?</strong></p><p>This transformation does not happen in a single step. Instead, Spring follows a structured metadata processing pipeline that converts classpath information into normalized container metadata.</p><p>At a conceptual level, the process can be understood as:</p><pre>→ Component Discovery<br>→ Metadata Extraction<br>→ Metadata Structuring<br>→ BeanDefinition Construction<br>→ Registry Registration</pre><p>Let’s walk through each stage.</p><h4>Component Discovery — Finding Candidates</h4><p>The first step is identifying classes that <em>might</em> represent beans.</p><p>This typically happens when the container processes configuration such as: @ComponentScan</p><p>Spring scans the classpath looking for candidate classes annotated with stereotypes like:</p><ul><li>@Component</li><li>@Service</li><li>@Repository</li><li>@Controller</li><li>@Configuration</li></ul><p>At this stage, Spring is <strong>not creating objects</strong>, nor even loading classes into the JVM. It is simply identifying potential components based on annotation presence.</p><p>This keeps scanning lightweight and fast.</p><h4>Metadata Extraction — Reading Class Information</h4><p>Once candidate classes are found, Spring inspects their metadata.</p><p>Instead of using reflection, Spring reads class bytecode directly to extract:</p><ul><li>Annotation types</li><li>Annotation attributes</li><li>Class hierarchy information</li><li>Interface implementations</li></ul><p>This allows Spring to gather structural information without triggering class loading or static initialization.</p><p>The result of this stage is raw annotation and class metadata describing the component.</p><h4>Metadata Structuring — Building Annotation Models</h4><p>The extracted metadata is then organized into structured representations that the framework can reason about.</p><p>From this structured metadata, Spring can determine things like:</p><ul><li>Whether the class should be registered as a bean</li><li>Lazy initialization settings</li><li>Scope characteristics</li><li>Qualifiers or primary markers</li><li>Configuration semantics</li></ul><p>At this point Spring understands the <em>intent</em> expressed by annotations, but still has not created a BeanDefinition.</p><h4>BeanDefinition Construction</h4><p>Next, Spring transforms structured metadata into BeanDefinition objects.</p><p>This step is crucial because it normalizes all configuration styles into one unified internal model.</p><p>Whether a bean originates from:</p><ul><li>XML configuration</li><li>Annotation scanning</li><li>Java configuration</li><li>Programmatic registration</li></ul><p>They all converge into the same abstraction which is BeanDefinition.</p><p>This abstraction contains everything the container needs to manage the bean lifecycle, including:</p><ul><li>Bean class name</li><li>Scope</li><li>Lazy flags</li><li>Dependency requirements</li><li>Factory information</li><li>Lifecycle callbacks</li></ul><p>From this point forward, the container operates purely on BeanDefinitions rather than original configuration sources.</p><h4>Registry Registration — Populating the Container Model</h4><p>Finally, constructed BeanDefinitions are registered inside the container’s internal registry.</p><p>This registry forms the container’s <strong>semantic model of the application</strong> — a complete description of:</p><ul><li>What objects exist</li><li>How they relate</li><li>How they should be created</li></ul><p>Only after this model is fully built does the container move on to instantiating beans during the later phases of the refresh() process.</p><p>This reinforces a central architectural principle:</p><blockquote><em>Spring does not build objects first. It first builds a metadata model of the application, and only then creates objects using those models.</em></blockquote><p>The stages described above represent a conceptual model of the definition phase. Internally, Spring executes this process through specialized post-processor mechanisms during the refresh() lifecycle. The actual implementation involves infrastructure components such as BeanDefinitionRegistryPostProcessor and ConfigurationClassPostProcessor.</p><h3>Why This Pipeline Matters</h3><p>Understanding this pipeline clarifies several behaviors observed earlier:</p><ul><li>Lazy beans still have BeanDefinitions</li><li>Scope is enforced by the container, not the class</li><li>Multiple configuration styles coexist seamlessly</li><li>Bean creation can be postponed or optimized</li></ul><p>Most importantly, it reveals that <strong>BeanDefinitions are the foundational data structure driving the entire container lifecycle.</strong></p><p>While the pipeline we’ve described may appear conceptual, it directly corresponds to an actual execution flow inside the Spring container. The transformation from annotations to BeanDefinitions is not an abstract idea — it happens as part of the ApplicationContext startup process. This process is orchestrated by a central lifecycle method called refresh(), which coordinates how definitions are prepared, processed, and eventually turned into real bean instances.</p><h3>Where BeanDefinitions Fit Inside the refresh() Lifecycle</h3><p>These definitions are not acted upon immediately. When the ApplicationContext starts, it goes through a structured startup process driven by a method called refresh(). This method orchestrates the entire container lifecycle — from preparing metadata to creating fully initialized beans.</p><p>During the early phase of refresh(), Spring collects and registers all BeanDefinition objects. At this stage, no actual bean instances exist. The container is still working with blueprints — not real objects.</p><p>Before instantiation begins, Spring provides an opportunity to modify these definitions through a mechanism known as BeanFactoryPostProcessor. These processors operate purely on metadata, allowing configuration values to be resolved or definitions to be adjusted before any objects are created.</p><p>Only after the definitions are finalized does Spring move into the instantiation phase. As beans are created, another extension point called BeanPostProcessor allows the container to process or wrap actual bean instances. This is how additional behavior — such as lifecycle callbacks or proxying — can be applied.</p><p>So to summarise:</p><p>When the Spring application starts:</p><ol><li>An ApplicationContext object is created.</li><li>refresh() is invoked.</li><li>Inside refresh():</li></ol><ul><li>The internal BeanFactory is prepared.</li><li>Configuration classes are processed.</li><li>Component scanning runs.</li><li>BeanDefinitions are created and registered.</li><li>BeanFactoryPostProcessors modify those definitions.</li><li>BeanPostProcessors are registered.</li><li>Non-lazy singleton beans are instantiated.</li></ul><p>4. The context becomes fully initialized and ready.</p><p>This is the real execution pipeline behind our conceptual model.</p><p>Lets do some experiments to identify the nature of beanDefinitions</p><h3>Small Experiment 1: Inspecting BeanDefinitions</h3><p>Lets look into a simple Spring Application to understand BeanDefinition better.</p><p>In this application, we use annotation-based configuration to define beans. (We will explore the internal mechanics of how these annotations are processed later in this article.)</p><p>We define two service classes.</p><pre>package com.example.app;<br>import org.springframework.context.annotation.Lazy;<br>import org.springframework.stereotype.Service;<br><br>@Service @Lazy<br>public class GreetingService {<br><br>    public GreetingService(){<br>        System.out.println(&quot;Constructor GreetingService&quot;);<br>    }<br><br>    public String greet(String name) {<br>        return &quot;Hello, &quot; + name + &quot;!&quot;;<br>    }<br>}</pre><p>and :</p><pre>package com.example.app;<br><br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class MessageService {<br><br><br>    public String formatMessage(String message) {<br>        return &quot;*** &quot; + message + &quot; ***&quot;;<br>    }<br><br>    public String getWelcomeMessage() {<br>        return &quot;Welcome to the minimal Spring application!&quot;;<br>    }<br>}</pre><p>Now let’s inspect the internal BeanDefinition objects registered in the container.</p><pre>    public static void main(String[] args) {<br><br>        System.out.println(&quot;========== CREATING APPLICATION CONTEXT ==========&quot;);<br>        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);<br>        System.out.println(&quot;========== CONTEXT CREATED ==========\n&quot;);<br><br>        String[] beanNames = context.getBeanDefinitionNames();<br>        System.out.println(&quot;Total BeanDefinitions: &quot; + beanNames.length + &quot;\n&quot;);<br><br>        // Focus on our application beans<br>        String[] appBeans = {&quot;greetingService&quot;, &quot;messageService&quot;, &quot;appConfig&quot;};<br><br>        for (String beanName : appBeans) {<br>            if (context.containsBeanDefinition(beanName)) {<br>                BeanDefinition bd = context.getBeanFactory().getBeanDefinition(beanName);<br>                printBeanDefinitionDetails(beanName, bd, context);<br>            }<br>        }<br>        context.close();<br><br>    }</pre><p>And the helper method:</p><pre>    private static void printBeanDefinitionDetails(String beanName, BeanDefinition bd, AnnotationConfigApplicationContext context) {<br>        System.out.println(&quot;╔════════════════════════════════════════════════════════&quot;);<br>        System.out.println(&quot;║ Bean Name: &quot; + beanName);<br>        System.out.println(&quot;╠════════════════════════════════════════════════════════&quot;);<br>        System.out.println(&quot;║ Bean Class Name: &quot; + bd.getBeanClassName());<br>        System.out.println(&quot;║ Scope: &quot; + bd.getScope());<br>        System.out.println(&quot;║ Is Singleton: &quot; + bd.isSingleton());<br>        System.out.println(&quot;║ Is Prototype: &quot; + bd.isPrototype());<br>        System.out.println(&quot;║ Is Lazy Init: &quot; + bd.isLazyInit());<br>        System.out.println(&quot;║ Is Abstract: &quot; + bd.isAbstract());<br>        System.out.println(&quot;║ Factory Bean Name: &quot; + bd.getFactoryBeanName());<br>        System.out.println(&quot;║ Factory Method Name: &quot; + bd.getFactoryMethodName());<br>        System.out.println(&quot;║ Init Method Name: &quot; + bd.getInitMethodName());<br>        System.out.println(&quot;║ Destroy Method Name: &quot; + bd.getDestroyMethodName());<br>        System.out.println(&quot;║ Role: &quot; + getRoleDescription(bd.getRole()));<br>        System.out.println(&quot;║ Description: &quot; + bd.getDescription());<br>}</pre><h3>Output</h3><p>For our two service classes, the container produces the following BeanDefinition metadata.</p><pre>╔════════════════════════════════════════════════════════<br>║ Bean Name: greetingService<br>╠════════════════════════════════════════════════════════<br>║ Bean Class Name: com.example.app.GreetingService<br>║ Scope: singleton<br>║ Is Singleton: true<br>║ Is Prototype: false<br>║ Is Lazy Init: true<br>║ Is Abstract: false<br>║ Factory Bean Name: null<br>║ Factory Method Name: null<br>║ Init Method Name: null<br>║ Destroy Method Name: null<br>║ Role: APPLICATION<br>║ Description: null<br>╠════════════════════════════════════════════════════════<br>║ Bean Instance Created: false<br>║ Bean Instance: NOT YET CREATED (BeanDefinition exists only)<br>╚════════════════════════════════════════════════════════<br><br>╔════════════════════════════════════════════════════════<br>║ Bean Name: messageService<br>╠════════════════════════════════════════════════════════<br>║ Bean Class Name: com.example.app.MessageService<br>║ Scope: singleton<br>║ Is Singleton: true<br>║ Is Prototype: false<br>║ Is Lazy Init: false<br>║ Is Abstract: false<br>║ Factory Bean Name: null<br>║ Factory Method Name: null<br>║ Init Method Name: null<br>║ Destroy Method Name: null<br>║ Role: APPLICATION<br>║ Description: null<br>╠════════════════════════════════════════════════════════<br>║ Bean Instance Created: true<br>║ Bean Instance: com.example.app.MessageService<br>╚════════════════════════════════════════════════════════</pre><h3>What Does This Output Reveal?</h3><p>This small experiment already exposes several important internal behaviors of the Spring container.</p><h4>BeanDefinition Exists Before Instantiation</h4><p>Even though GreetingService is marked as @Lazy, its BeanDefinition is fully registered inside the container.</p><p>Only the <em>object instance</em> is deferred.</p><p>This clearly demonstrates a fundamental principle:</p><blockquote><em>Spring first builds BeanDefinitions. Only later does it create actual bean instances.</em></blockquote><p>The BeanDefinition belongs to the <strong>definition phase</strong>.<br> Object creation belongs to the <strong>instantiation phase</strong>.</p><p>These are two separate steps in the container lifecycle</p><h4>Scope Is Metadata, Not Object State</h4><pre>Scope: singleton<br>Is Singleton: true</pre><p>The GreetingService class itself has no awareness that it is a singleton. Which means the object does not enforce singleton behavior.</p><p>Instead:</p><blockquote><em>Singleton behaviour is enforced by the container based on the BeanDefinition metadata.</em></blockquote><p>This is a subtle but critical architectural idea. The object is just a plain Java class. The container provides the semantics.</p><h4>Lazy Initialisation Proves the Two-Phase Model</h4><p>MessageService is instantiated during context initialisation.</p><p>GreetingService is not.</p><p>Why?</p><p>Because AnnotationConfigApplicationContext pre-instantiates all non-lazy singleton beans during refresh().</p><p>When a bean is marked as @Lazy, its BeanDefinition is still registered, but instantiation is postponed until getBean() is called. This clearly shows BeanDefinition registration and bean instantiation are independent steps.</p><h4>The Definition Phase vs The Instantiation Phase</h4><p>By inspecting the output, we can now clearly separate two distinct phases inside the container lifecycle:</p><p><strong>1. Definition Phase</strong></p><ul><li>Configuration metadata is discovered.</li><li>BeanDefinitions are constructed.</li><li>BeanDefinitions are registered inside the container.</li><li>No user beans are necessarily created yet.</li></ul><p><strong>2. Instantiation Phase</strong></p><ul><li>The container materializes BeanDefinitions into actual objects.</li><li>Dependencies are resolved.</li><li>Initialization callbacks are triggered.</li><li>Lifecycle rules are enforced.</li></ul><p>Understanding this separation is crucial.</p><h4>What does this experiment reveals internally</h4><p>If we step back and look at this closely we can understand that the spring does not treat any of the user created classes special. It does not embed lifecycle rules inside the class or does not modify it to be singleton.</p><p>Instead what spring does is builds a <strong>metadata model</strong> that describes how each object should behave inside the container. This <strong>metadata model </strong>is what we call BeanDefinition.</p><h3>What’s Next?</h3><p>We’ve explored how Spring transforms configuration metadata into BeanDefinitions — the internal blueprint the container uses to manage beans. We’ve seen that this happens before any actual objects are created.</p><p>In the <a href="https://medium.com/p/a88878241fa1?postPublishedType=initial">next part</a>, we’ll move forward in the container lifecycle and examine the instantiation phase: how Spring transforms these BeanDefinition blueprints into actual, dependency-injected, fully-initialized objects ready for use in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c46cf01782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Framework: Part 2]]></title>
            <link>https://medium.com/@sathira97/understanding-spring-framework-part-2-e205ada1356e?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/e205ada1356e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 01:19:52 GMT</pubDate>
            <atom:updated>2026-02-17T03:55:26.300Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inside the Spring IoC Container and ApplicationContext</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWQ5TiXIEMxAsqzS5htitg.png" /></figure><p>In the previous article of this series we gained a basic understanding about concepts like IoC, DI and Spring Container. I recommend you read <a href="https://medium.com/@sathira97/understanding-spring-framework-part-1-246a5a775be5"><strong>Part 1</strong></a><strong> </strong>first. In this part, we will focus on understanding the Spring Container in more depth, with particular attention to its main abstractions: <strong>BeanFactory</strong> and <strong>ApplicationContext</strong>.</p><h3><strong>What is Spring IoC Container</strong></h3><p>The Spring IoC container is a runtime <strong>infrastructure component</strong> responsible for creating, configuring, and managing application objects (beans), eliminating the need for manual object creation and dependency management. In practice, <strong>ApplicationContext</strong> is used almost exclusively in modern Spring applications.</p><h4><strong>Responsibilities of the IoC Container</strong></h4><ul><li><strong>Creates</strong> <strong>objects</strong> (beans) based on configuration</li><li><strong>Wires</strong> <strong>them</strong> <strong>together</strong> (resolves dependencies)</li><li><strong>Manages</strong> <strong>their</strong> <strong>lifecycle</strong> (initialization, destruction)</li><li><strong>Serves</strong> <strong>them</strong> <strong>on</strong> <strong>demand</strong> (or eagerly at startup, depending on configuration)</li></ul><h4><strong>The</strong> <strong>Two</strong> <strong>Types</strong> <strong>of</strong> <strong>IoC</strong> <strong>Containers</strong></h4><p>Spring IoC Container is defined by the BeanFactory interface.<br>ApplicationContext is a sub-interface that extends BeanFactory and adds enterprise-level services required by modern applications</p><h4>BeanFactory</h4><p>BeanFactory represents the minimal IoC container contract and is primarily used internally by the framework rather than directly by application developers. It is the engine that provides the basic machinery for:</p><ul><li><strong>Object Instantiation:</strong> Creating Java objects from your classes.</li><li><strong>Dependency Injection:</strong> Wiring those objects together.</li><li><strong>Lifecycle Management:</strong> Handling the birth (initialization) and death (destruction) of objects.</li></ul><h4>ApplicationContext</h4><p>It is a sub-interface that <strong>extends</strong> BeanFactory, inheriting all its core DI capabilities while adding the enterprise-level services that modern applications demand.</p><ul><li><strong>Eager Initialization:</strong> Unlike the “lazy” BeanFactory, it creates all singletons at startup. This ensures that if a dependency is missing, your application fails immediately (Fail-Fast) rather than crashing during a live request.</li><li><strong>Automated Annotation Processing</strong>: ApplicationContext automatically registers the necessary BeanPostProcessors that detect and process annotations such as @Value and @Autowired</li><li><strong>Framework Integration:</strong> It adds built-in support for AOP (Aspect Oriented Programming), Internationalization (i18n), and Application Events.</li></ul><p>By separating the core IoC contract (BeanFactory) from higher-level application services (ApplicationContext), Spring achieves a clean architectural layering. This allows the framework to remain lightweight at its core while still providing the rich infrastructure required by enterprise applications.</p><h3>Creating an ApplicationContext</h3><p>Up to this point, we have discussed the Spring IoC container at a conceptual level. However, the container does not exist automatically. At runtime, it must be explicitly created so that Spring can begin managing application beans.</p><p>In a core Spring application, the container can be created using the following line of code:</p><pre>ApplicationContext context =<br>        new AnnotationConfigApplicationContext(AppConfig.class);</pre><p>This single line is where Spring creates the <strong>actual IoC container</strong>.</p><p>Let’s break this down what is happening here.</p><ul><li><strong>ApplicationContext</strong> is the interface that represents the Spring container. By programming to this interface, our application remains decoupled from any specific container implementation, allowing flexibility and extensibility.</li><li><strong>AnnotationConfigApplicationContext</strong> is a concrete implementation of ApplicationContext. This particular implementation understands <strong>Java-based, annotation-driven configuration</strong>, making it suitable for modern Spring applications.</li><li><strong>AppConfig.class</strong> is the configuration source. It provides the metadata Spring needs to understand what the application looks like — which beans exist and how they should be wired together.</li></ul><p>At this point, the IoC container is initialized, and Spring is ready to discover, create, and manage application beans.</p><h4>Other ApplicationContext Implementations (Overview)</h4><p>Spring provides multiple concrete implementations of ApplicationContext to support different ways of defining application configuration. While the <strong>core IoC behavior remains the same</strong>, each implementation has differences in <strong>how and where it reads bean definitions from</strong>.</p><p>Below is a high-level overview of the most commonly encountered implementations.</p><ul><li><strong>AnnotationConfigApplicationContext</strong><br> An ApplicationContext implementation that reads configuration from Java classes using annotations such as @Configuration, @Bean, and @ComponentScan. It is commonly used in standalone Spring applications and forms the conceptual foundation for modern Spring configuration.</li><li><strong>ClassPathXmlApplicationContext</strong><br> Loads bean definitions from XML configuration files located on the classpath. This approach was widely used in early Spring applications and is still encountered in legacy systems.</li><li><strong>FileSystemXmlApplicationContext</strong><br> Similar to the classpath-based variant, but reads XML configuration files from the filesystem instead. This allows configuration to be externalized outside the application’s packaged artifacts.</li><li><strong>AnnotationConfigWebApplicationContext</strong><br> A web-aware ApplicationContext designed for traditional Spring MVC applications. It integrates with the Servlet API and supports web-specific scopes such as request and session.</li><li><strong>GenericApplicationContext</strong><br> A flexible, low-level implementation that allows bean definitions to be registered programmatically. It is commonly used in framework development and advanced customization scenarios.</li></ul><p>While these implementations serve different use cases, they all adhere to the same ApplicationContext contract. The choice of implementation primarily depends on <strong>how configuration metadata is supplied</strong>, not on how dependency injection or lifecycle management works internally.</p><h3>Conclusion</h3><p>In this article, we explored the Spring IoC container in detail. We looked at what the container is responsible for, why ApplicationContext is the primary container used in modern Spring applications, and how a Spring application creates and initializes this container at runtime. We also reviewed the different ApplicationContext implementations and the role each one plays.</p><p>At this stage, we understand how the container is created — but it doesn’t yet know what to manage.</p><p>The next obvious question is: <strong>how does Spring know which beans to create?</strong></p><p>In <a href="https://medium.com/@sathira97/understanding-spring-framework-part-3-b0c46cf01782"><strong>Part 3</strong></a>, we will focus on defining beans inside the container. We will look at Java-based configuration using @Configuration and @Bean, and see how Spring discovers and registers application components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e205ada1356e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Framework: Part 1]]></title>
            <link>https://medium.com/@sathira97/understanding-spring-framework-part-1-246a5a775be5?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/246a5a775be5</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 10:32:12 GMT</pubDate>
            <atom:updated>2026-02-10T01:28:07.517Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>By Sathira Basnayake</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ln9FChnfyl88EnNulXLCA.png" /></figure><p>Many developers jump straight into Spring Boot annotations without understanding the engine running beneath them. This series tries to understand the core architecture of the Spring Framework. Before we build microservices, we must master the fundamentals: <strong>Inversion of Control (IoC)</strong>, <strong>Dependency Injection (DI)</strong>, and the <strong>Spring Container</strong>.</p><h3>Inversion of Control (IoC)</h3><p>This is the main architectural shift in Spring compared to traditional Java development. Let’s deep dive into why we need IoC, what it is, and how to make use of it.</p><h3>The Problem IoC Solves</h3><p>In a standard Java project, Java objects are created and managed by the developer. So, what’s the problem?</p><p>Think of it like this: Imagine you have a Car class which needs an Engine as a dependency. In a traditional approach, the developer must create the Engine object manually using the new keyword before creating the car.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        // 1. The developer has to create the dependency first<br>        Engine v8 = new Engine();<br>        <br>        // 2. The developer has to manually put it inside the Car<br>        Car myCar = new Car(v8);<br>        <br>        // 3. The developer is responsible for holding onto this object<br>        myCar.drive();<br>    }<br>}</pre><p><strong>The Pain Points:</strong></p><ul><li><strong>Tight Coupling:</strong> If you want to change the Engine to an ElectricMotor, you have to go into your Main code and rewrite it.</li><li><strong>Complexity:</strong> In a real app with 100 classes, your main method becomes a nightmare of thousands of new keywords.</li></ul><h3>The Solution</h3><p>In Spring, we change who creates, manages, and destroys the Java objects. We give that control to the Spring Framework itself. This “inversion” of responsibility is what we call <strong>Inversion of Control</strong>.</p><p>In a microservices architecture, IoC is what allows us to swap implementations (e.g., swapping a Mock Database for a Real Database) via configuration without rewriting a single line of business logic.</p><p><strong>In simple words:</strong></p><blockquote><em>“Inversion of Control means we delegate the creation, management, and destruction of objects to the framework itself, instead of doing it manually as developers.”</em></blockquote><h3>Dependency Injection (DI)</h3><p>Now that we understand we need to give up control (IoC), the next question is: <em>How exactly does the framework take control?</em></p><p>The answer is <strong>Dependency Injection</strong>.</p><p>If IoC is the principle, Dependency Injection is the pattern we use to implement it. It connects your objects together so you don’t have to.</p><p><strong>How it works:</strong> In our previous example, the Car needed an Engine.</p><ul><li><strong>Without DI:</strong> The Car creates the engine itself (new Engine()).</li><li><strong>With DI:</strong> The framework creates the Engine separately, creates the Car separately, and then <em>injects</em> the engine into the car.</li></ul><p>The Car doesn&#39;t know (and doesn&#39;t care) where the engine came from. It just knows that when it started up, an engine was provided. This makes your code loosely coupled and incredibly easy to test.</p><p>We have three main types of DI:</p><ul><li>Field Injection</li><li>Setter Injection</li><li>Constructor Injection</li></ul><h4>1. Field Injection</h4><p>This is where you define the dependency and add an annotation to tell the Spring Framework to inject it.</p><pre>@Service<br>public class Car {<br>    @Autowired // Marks this field for dependency injection<br>    private Engine engine;<br>    <br>    // ... logic ...<br>}</pre><p>Here, Spring uses <strong>Reflection</strong> to bypass the private access modifier and set the field directly. While it looks clean and simple, <strong>this is not the recommended way</strong> to do DI in modern Spring development.</p><ul><li>It makes writing Unit Tests difficult (you have to use reflection hacks to test the class).</li><li><strong>It hides dependencies.</strong> A class with 10 injected fields looks clean, but it violates the Single Responsibility Principle. Constructor injection forces you to see the ugliness of too many dependencies.</li></ul><h4>2. Setter Injection</h4><p>This is where you use a setter method to handle the injection.</p><pre>@Service<br>public class Car {<br>    private Engine engine;<br>@Autowired<br>    public void setEngine(Engine engine) {<br>        this.engine = engine;<br>    }<br>}</pre><p>This is also not widely used. We typically only use this method if the dependency is <strong>optional</strong> (meaning the Car can still work without an Engine, or the Engine might change while the app is running) or to resolve <strong>Circular Dependencies</strong>.</p><h4>3. Constructor Injection (The Gold Standard)</h4><p>This is the recommended, modern approach. In this method, we use the constructor to inject the dependency.</p><pre>@Service<br>public class Car {<br>    // 1. We can make the field FINAL (Immutable)<br>    private final Engine engine;<br>    // 2. We pass it in the constructor<br>    // (Note: @Autowired is optional here since Spring 4.3)<br>    public Car(Engine engine) {<br>        this.engine = engine;<br>    }<br>}</pre><p><strong>Why is this the Gold Standard?</strong></p><ul><li><strong>Immutability:</strong> The dependency is final, so it cannot be changed once the object is created.</li><li><strong>No Nulls:</strong> You cannot create a Car without passing an Engine. The compiler ensures your object is always in a valid state.</li><li><strong>Easy Testing:</strong> You don’t need Spring to test this class. You can simply call new Car(new MockEngine()) in your JUnit tests.</li></ul><h3>Spring Bean</h3><p>A Spring Bean is a Java object that is <strong>instantiated, assembled, and managed</strong> by the Spring IoC Container</p><ul><li>A <strong>Normal Java Object</strong> is created and managed by the developer (using new) and destroyed by the Garbage Collector.</li><li>A <strong>Spring Bean</strong> is created, managed, and destroyed by the Spring Container.</li></ul><p><strong>In simple words:</strong></p><blockquote><em>“In Spring, a Bean is simply a Java object. The difference is that the Spring Container creates it and manages it until it is destroyed.</em></blockquote><h3>Spring Container</h3><p>The Spring Container is the heart of the framework. It is the engine that actually performs the Inversion of Control (IoC). When a Spring application is running, this is the environment where Spring Beans live.</p><p><strong>What does it actually do?</strong> The Container is responsible for the entire lifecycle of your objects:</p><ul><li><strong>Instantiation:</strong> It creates the objects (conceptually calling new in the background).</li><li><strong>Configuration:</strong> It sets the properties and values the objects need.</li><li><strong>Assembly (Wiring):</strong> This is the magic part. If your Car bean needs an Engine bean, the Container finds the engine and injects it automatically.</li><li><strong>Lifecycle Management:</strong> It manages the object from creation to destruction, ensuring resources are cleaned up when the application shuts down.</li></ul><p><strong>In simple terms:</strong></p><blockquote><em>“You give the Container your classes, and it returns a fully configured application.”</em></blockquote><h3>What’s Next?</h3><p>Now that we have a high-level understanding of the “Magic” behind Spring (IoC and DI), it’s time to look at the code.</p><p>In <a href="https://medium.com/@sathira97/understanding-spring-framework-part-2-e205ada1356e?postPublishedType=repub"><strong>Part 2</strong></a>, we will dive deep into the <strong>Spring IoC Container</strong>. We will explore the ApplicationContext, look at how to configure it, and see exactly how to tell Spring to create our beans using @Configuration and @Bean.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=246a5a775be5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Pattern (Part 1)]]></title>
            <link>https://medium.com/geekculture/strategy-pattern-part-1-8ad69ee49a22?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ad69ee49a22</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 11:24:42 GMT</pubDate>
            <atom:updated>2026-02-08T04:44:30.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategy Pattern: Part 1</h3><p>Hi, In this article we will look into a very important design pattern which is called the strategy pattern which is a behavioral design pattern in a more practical way.</p><p>The main idea of this design pattern is we have a task to do and we have several ways (algorithms) of doing that same task and the we get the ability to use these algorithms interchangeably according to the context in the run time. As a simple example we want to sort a list and we have many algorithms to do that task and also we can select the right algorithms for the right situation using the strategy pattern. Now lets look into the main parts of the strategy pattern.</p><h4>The Problem: The If-Else Nightmare</h4><p>This is actually very common problem developers face. Lets say for some task we want to conditionally choose different ways of doing the same thing. Initially we write the code in single class with if else statements and it may seem harmless at first. But when the code matures and we need to add more code to the same class which violates a very important principle in software engineering called the Open/Closed Principle. This principle basically says that our code should be open for extension but closed for modification. As a example of a payment service, if we want to add a new feature, we are forced to modify the existing, working code. This increases the risk of introducing bugs into the parts of the system that were already working fine. So, if we make a mistake in the “Crypto” logic, we might accidentally break the “Credit Card” logic.</p><p>Now the next question is, how do we solve this? We need a way to separate these algorithms so they don’t tangle up with each other. This is exactly where the Strategy Pattern comes into play. It allows us to remove this “If-Else Nightmare” and replace it with a clean, flexible structure where we can add new logic without touching the old code.</p><h4>Definition</h4><p>Simply put, the Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This allows the algorithm to vary independently from the clients that use it, letting you switch logic at runtime based on the context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-nVCSRsfRmICe6-9riWvw.png" /></figure><h4>Key Components of Strategy pattern</h4><p><strong>Strategy (Interface/Abstract Class) </strong>: This is the interface which defines the common methods which is common to all the concrete strategy classes.</p><p><strong>Concrete Strategy : </strong>These are the concrete implementations of the different strategies. This implements the methods define in the interface in a unique way for that specific strategy.</p><p><strong>Context</strong>: This is the class where we uses the various strategies via the interface. This will delegate the task into one of the strategy implementation. This will choose the correct strategy in the runtime according to the specific scenario and always work with the interface.</p><h3>Practical Example</h3><p>I will explain the strategy pattern using simple vanilla java example with a payment service example. First lets look into the before code with if-else.</p><pre>public class PaymentService {<br>    public void processPayment(String type, double amount) {<br>        if (type.equalsIgnoreCase(&quot;CREDIT_CARD&quot;)) {<br>            System.out.println(&quot;Processing credit card payment of &quot; + amount);<br>            // Logic for validating card, charging, etc.<br>        } else if (type.equalsIgnoreCase(&quot;PAYPAL&quot;)) {<br>            System.out.println(&quot;Processing PayPal payment of &quot; + amount);<br>            // Logic for connecting to PayPal API...<br>        } else if (type.equalsIgnoreCase(&quot;GOOGLE_PAY&quot;)) {<br>            System.out.println(&quot;Processing Google Pay payment of &quot; + amount);<br>            // Logic for Google Pay...<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid payment type&quot;);<br>        }<br>    }<br>}</pre><p>As you can see in the above code if we want to add bit coin support we have to edit the already tested service class. This violates the <strong>Open/Closed Principle.</strong></p><p>Lets use Strategy pattern to solve this problem.</p><h4>Step 1: The Strategy Interface</h4><p>This defines the contract.</p><pre>public interface PaymentStrategy {<br>    void pay(double amount);<br>}</pre><h4>Step 2: Concrete Strategies</h4><p>These are the specific algorithms. If you need to add Bitcoin later, you just create a new class. <strong>You never touch the existing code.</strong></p><pre>// Implementation A<br>public class CreditCardStrategy implements PaymentStrategy {<br>    private String cardNumber;<br><br>    public CreditCardStrategy(String cardNumber) {<br>        this.cardNumber = cardNumber;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(amount + &quot; paid with Credit Card (&quot; + cardNumber + &quot;)&quot;);<br>    }<br>}<br><br>// Implementation B<br>public class PayPalStrategy implements PaymentStrategy {<br>    private String email;<br><br>    public PayPalStrategy(String email) {<br>        this.email = email;<br>    }<br><br>    @Override<br>    public void pay(double amount) {<br>        System.out.println(amount + &quot; paid using PayPal (&quot; + email + &quot;)&quot;);<br>    }<br>}</pre><h4>Step 3: The Context</h4><p>This class doesn’t care <em>how</em> the payment happens, only that it <em>does</em> happen.</p><pre>public class PaymentContext {<br>    private PaymentStrategy strategy;<br><br>    // We can change the strategy at runtime<br>    public void setPaymentStrategy(PaymentStrategy strategy) {<br>        this.strategy = strategy;<br>    }<br><br>    public void executePayment(double amount) {<br>        if (strategy == null) {<br>            throw new IllegalStateException(&quot;Payment strategy not set&quot;);<br>        }<br>        strategy.pay(amount);<br>    }<br>}</pre><h3>Pros of the Strategy Pattern</h3><ul><li>We can swap algorithms used inside an object at runtime very easily</li><li>Better isolation on the implementation details of an algorithm from the code that uses it.</li><li>We can add new implementations without breaking the Open/Closed principle</li><li>Eliminates long if-else or switch blocks in the Context, making its code cleaner and more focused.</li><li>Concrete strategies can be testes independently with better isolation.</li></ul><h3>Cons of the Strategy Pattern</h3><ul><li>Introduces lots of new classes and which can add complexity to the system.</li><li>Clients should be aware of the strategies that is available and how to choose a strategy.</li></ul><h3>Alternative approaches and variations</h3><ul><li><strong>Functional Programming (Lambdas):</strong> Since PaymentStrategy is a Functional Interface (it has only one abstract method), we don&#39;t always need to create full classes. For simple logic, we can pass behavior directly using Java 8 Lambdas:</li></ul><pre>// Passing logic inline without a concrete class <br>context.setPaymentStrategy(amount -&gt; System.out.println(&quot;Paid &quot; + amount + &quot; via Bitcoin&quot;));</pre><ul><li><strong>Enum-Based Strategies:</strong> for logic that is stateless and unlikely to change often, you can implement the Strategy interface directly on a Java Enum. This keeps logic centralized but can violate Open/Closed principles if the enum grows too large.</li><li><strong>Spring Boot &amp; Dependency Injection (The Professional Way):</strong> In a real-world enterprise application, we rarely manually instantiate strategies (e.g., new PayPalStrategy()). Instead, we let the Spring IoC container manage them. We can inject a Map&lt;String, PaymentStrategy&gt; or a List&lt;PaymentStrategy&gt; directly into our Context, allowing us to select the correct bean dynamically at runtime without valid if-else blocks.</li></ul><h3>Conclusion</h3><p>The Strategy Pattern is more than just a way to remove if-else blocks; it is a fundamental shift toward writing cleaner, scalable, and maintainable code. By decoupling the decision-making logic from the implementation details, we adhere to the Open/Closed Principle, ensuring that our systems can grow without breaking existing functionality.</p><p>In this article, we covered the “Vanilla Java” implementation to understand the core mechanics of the pattern. However, in modern enterprise development, we rarely manage these instances manually.</p><p>In <strong>Part 2</strong>, we will take this concept further by integrating the Strategy Pattern with <strong>Spring Boot</strong>. We will explore how to leverage Dependency Injection and Map&lt;String, Service&gt; injection to make strategy selection dynamic, clean, and production-ready. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ad69ee49a22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/strategy-pattern-part-1-8ad69ee49a22">Strategy Pattern (Part 1)</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression for Machine Learning]]></title>
            <link>https://medium.com/geekculture/logistic-regression-for-machine-learning-22af1d008186?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/22af1d008186</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[binary-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 22:21:25 GMT</pubDate>
            <atom:updated>2021-08-26T07:57:22.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*A_D47lu42P_XLf8lzdhNQg.png" /></figure><p>Hi, I’m Sathira Basnayake and in this article, we will look into the basics of logistic regression for Machine learning. As we know the machine learning has 3 major categories call supervised learning, unsupervised learning and reinforcement learning. When we talk about supervised learning, classification and regression are the most used techniques. Logistic regression comes into play with classification.</p><p>To understand logistic regression properly I think it is better to have some idea about regression as well. So if you are not familiar with that concept I suggest you first get some idea about it and come back. For sake of simplicity, we will take a one attribute linear regression example. The most commonly used example would be house predicting and we will assume a data set with the area(X) and the house price(Y). In this case, price is the target variable. We may have a data set like this. As you have an idea about linear regression you would know how to find the most suitable line for prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jO4cNNW2XokovO6777TuNQ.png" /></figure><p>The function of the line would be something like “<em>wx + b = y_hat</em>”. You know to find the best w and b values using gradient descent or any other method. We use MSE(Mean Square Error) as our loss function in that scenario. But what if the target variable is a variable with class values.</p><p>In such a scenario we need to use Logistic Regression. It’s basically a classification algorithm that can be used to perform binary classification using independent variables. So if you know linear regression you may think why we can’t use linear regression as it is and draw the line and after that divide the outcomes according to a threshold. Actually, It can be done but not very effective. So what we do is take the same “<em>wx + b = y_hat</em>” kind formula and feed it into the Sigmoid Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*BwZmaMBaVW8f8lBAQUoytw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*rMcXM1YgsRqZLgai8CsarA.png" /></figure><p>This is what we call the sigmoid function. We have to get the predicted value using “<em>wx + b = y_hat</em>” like function and feed that to the sigmoid function. By doing that we can always get a value between 0 and 1. So by using a threshold like 0.5 we can predict that values above 0.5 belong to class A and values below 0.5 will belong to class B. (We use 0.5 most of the time. But we have to move the threshold in certain cases).</p><p>Now the next question is how do we optimize the parameters. What do we have to use as the cost function? Actually, we cannot use MSE as our cost function because the cost function is not convex. So if we try to use MSE on logistic regression we would probably trap in a local minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*AYJPyFjfyPas-oQxG-49nw.png" /></figure><p>So we have to find a convex cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*_gxyHUR4-Z3h80Ie9hsSHQ.png" /></figure><p>This is the cost function which we use in logistic regression. This function is convex and if you are interested you can observe more about the mathematical side of this subject. This is another form of the same cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_D_k9MYajw03ifomEmAcYg.png" /><figcaption>(Andrew ng’s course)</figcaption></figure><p><em>As we know the cost function, the next step is to find the best w and b values that minimize the cost function</em>. To do that we use the gradient descent algorithm. In this article, we are not going to discuss gradient descent in detail. But basically what it does is finds the minimum of a differentiable function through an iterative optimization approach. In the beginning, we choose initial guess values to w and b and after that, we minimize the error with every iteration where we can finally get the optimum w and b values. The gradient descent algorithm is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*fsjiPJmqA9FNkB5jIZ_14w.png" /><figcaption>(Andrew ng’s course)</figcaption></figure><p>In the above image, we can take theta0 as b and theta1 as w in our scenario. alpha is called the learning rate which is a hyperparameter that determines the speed. In this algorithm, in every iteration, some portion of the derivative of the cost function is reduced by the current value. As it always points to the steepest descent direction b every iteration the cost function will direct toward its global minima. Finally, at the end of the iterations we get tuned parameters. That is s a very basic introduction to gradient descent.</p><p>So after tuning the parameters we got our model. Now we can use the model to predict new values according to our needs. In the practical scenario, there are much more things to consider apart from these basic core concepts.</p><p>This article gives you a basic idea about the theory behind logistic regression for machine learning. This does not cover any practical aspects of the subject. Now we have reached the end of our article. Your comments and feedback are warmly welcome. I highly encourage you to show me if there are any mistakes with my content. Thank You all. Have a nice day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22af1d008186" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/logistic-regression-for-machine-learning-22af1d008186">Logistic Regression for Machine Learning</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Introduction for Beginners]]></title>
            <link>https://medium.com/codex/git-introduction-for-beginners-4286b1420f59?source=rss-25621e89f432------2</link>
            <guid isPermaLink="false">https://medium.com/p/4286b1420f59</guid>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Sathira Basnayake]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 22:22:20 GMT</pubDate>
            <atom:updated>2021-08-20T01:10:52.049Z</atom:updated>
            <content:encoded><![CDATA[<h4>(Part 1)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEeRdnzasX_NzEJ8t0LXqw.jpeg" /></figure><p>Hi, I’m Sathira Basnayake and we will take a good look at basic concepts of Git in this article. Git is basically the most popular version control system in the world. Version control is used to track and manage changes of our projects and Version Control systems are software tools to do that task.</p><p>With Git we can record the changes with our code overtime in a special database called repository and we can see what changes are done and if we screw something we can easily revert the changes and come into a previous stage. Without Git we have to save multiple copies of our projects and manually manage them. If we work as a team we will have to exchange codes with something like email and manually merge them. But with Git we can easily work as a team and keep track of our code. I think now you have a good idea about why we must use Git in our projects.</p><p>Git is a distributed version control system which means every team member has a local repository in there machines unlike in centralized systems. So know we get the problem why git is the most used version control system? It is because git is free, open source, fast, scalabe. We can use git in the command line as well as in GUI. In this article I’m going to use the command line method.</p><p>There are several methods to install git in our machine and <a href="https://www.atlassian.com/git/tutorials/install-git">here</a> is a very good guide. You can refer it and successfully install Git in your machine regardless of the OS. After you installed Git in your machine you can use Git to a new project or an existing project.</p><p>Now we will look into how do we initialize a new Git repository. Navigate to where you want to start the project and enter the <strong>git init command</strong>.</p><pre>sathira@kali:~$ git init</pre><p>Once you enter this command a new git repository will be created alone with .git file and new master branch(we will talk about the branches in the future). This .git sub directory is hidden because it contains the meta data and we don’t have to touch it. To turn an existing project into a git repository we can simply run the same command in the directory which contains the project. And also we can do like this.</p><pre>sathira@kali:~$ git init &lt;project directory&gt;</pre><p>Now we have talk about how we can initialize a git repositary locally into a existing project or for a new project. Now we will talk about remote repositories to get the big picture and understand the full workflow. When we talk about remote repositories the GitHub comes into play.</p><p><strong>GitHub</strong> is basically a cloud base online database which allows to keep track and share Git version control projects. So we can push over local repository to GitHub which is in the cloud and share and manage it with our teammates. That is how actually we use version control systems to work as a team. So once we push our local repository into GitHub it contains the remote repository which can be access and manage by our other team members. And you may be wondering is GitHub is the only online platform which can do this. No , there are other platforms like Bitbucket which does the same. But we will go with GitHub in this article.</p><p>But what if a project is already in GitHub central repository and we want to take that project int our local machine. That is where <strong>git clone</strong> command comes into the play. We can only run this command once and after that the user gets a working copy and he can use git to manage the version control locally.</p><pre>git clone &lt;repo url&gt;</pre><p>I think now is the best time to get a better idea about the workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*E7ZcCK7M6ADhT_ALygXrGA.jpeg" /><figcaption>Git workflow</figcaption></figure><p>As we can see in the above image(Git commands are shown with arrows and we will discuss those one by one) our local directory has 3 main parts.</p><ul><li>Working Directory</li><li>Staging Area</li><li>Local Repository</li></ul><p>In here the working directory is the directory which we create the .git sub directory. That is where we build our project. After some changes in our code we have to add the modified files into the staging state. To do that we use <strong>add command</strong>.</p><pre>sathira@kali:~$ git add &#39;filename&#39;</pre><pre>sathira@kali:~$ git add .</pre><p>We use git add . to add al the changes int staging area in one go. After we add the changes into our staging are we can again review over work before committing. Once we have add all the modified files and we are happy we can commit the snapshot into our local repository. This staging area allows us to review our work before committing. To commit the changes into the local repository we use <strong>commit command.</strong></p><pre>sathira@kali:~$ git commit - m &quot;initial commit&quot;</pre><p>In here when we do the commits we have to give a very meaningful message so if we were to check the commit history for some reason we can do it easily. Evey commit has a unique id and some meta information and the complete snapshot. So if we want to go to a previous state we can do that.</p><p>Now we will talk about how can we configure our local repositories in sync with remote repositories. For that we have to do some basic configurations.To do that we have to add a remote repo URL to your local git config</p><pre>sathira@kali:~$ git remote add &lt;remote_name&gt; &lt;remote_repo_url&gt;</pre><p>This command will map remote repository at to a ref in your local repository under . Once you have mapped the remote repository you can push local branches to it.</p><p>By using this command we have map a remote repository to our local repository. Now we can push local branches to the remote repository by using <strong>git push command</strong>.</p><pre>sathira@kali:~$ git push &lt;remote&gt; &lt;branch&gt;</pre><p>After that when we want to get the changes done in the remote repository to our local repository we use <strong>git pull command. </strong>It immediately updates the local repository to match that content. Actually what git pull do is executing two git commands. Those are git fetch and git merge. As a good practice we always have to do a git pull before we push over modifications to the remote repository.</p><pre>sathira@kali:~$ git pull &lt;remote&gt;</pre><p>After we do this git pull and if there is conflicts we have to handle those manually. In this article we are not going to discus about merge conflicts.</p><p>Now I hope you all have a good basic idea about Git and GitHub and how to manage a project with Git. In this article we have discussed about eight git commands. Those are<strong> git init, git clone, git add, git commit, git push, git pull, git remote add</strong>. These are the basic commands and there are lot more. We haven’t discussed about git branches, merge conflicts , GitHub pages, GitHub actions kind of advanced topics in this article. We will discuss those topics in the future articles. If you have any suggestions or criticism feel free to contact <a href="https://www.linkedin.com/in/sathira-basnayake-56aa41193/">me</a> or you can drop a comment. Thank You very much and stay safe .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4286b1420f59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/git-introduction-for-beginners-4286b1420f59">Git Introduction for Beginners</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>