<?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 Robinson Githae on Medium]]></title>
        <description><![CDATA[Stories by Robinson Githae on Medium]]></description>
        <link>https://medium.com/@robindamisi?source=rss-a3d688a986e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wR-8Abq9Bztk8R9C_SYfXw.jpeg</url>
            <title>Stories by Robinson Githae on Medium</title>
            <link>https://medium.com/@robindamisi?source=rss-a3d688a986e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:39:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robindamisi/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[Integrating Swagger and Redoc Documentation for maven based spring boot projects Beginner to Expert…]]></title>
            <link>https://medium.com/@robindamisi/integrating-swagger-and-redoc-documentation-for-maven-based-spring-boot-projects-beginner-to-expert-268218052b67?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/268218052b67</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[swagger-ui]]></category>
            <category><![CDATA[redoc]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 21:05:48 GMT</pubDate>
            <atom:updated>2025-07-03T21:05:48.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating Swagger and Redoc Documentation for maven based spring boot projects Beginner to Expert Guide for all Developers</h3><h3>📖 What is Swagger?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqNkvXSlj4-H7lMsvmdi3g.png" /><figcaption>Swagger UI</figcaption></figure><p><strong>Swagger</strong> is a powerful set of tools and specifications designed to help developers document, design, and test RESTful APIs. It’s now part of the <strong>OpenAPI Specification (OAS)</strong>, which has become the industry standard for describing APIs.</p><p>With Swagger, you can:</p><ul><li>✅ Automatically generate interactive API documentation from your Spring Boot code.</li><li>✅ Allow users and developers to test endpoints directly from the browser.</li><li>✅ Ensure your API is well-structured and easy to understand.</li></ul><h3>Why Use Swagger?</h3><p>Imagine sharing your backend API with frontend teams, mobile developers, or third-party consumers. Instead of writing complex API documents manually, Swagger does it for you — <strong>auto-generated, always up-to-date, and interactive</strong>.</p><blockquote><em>💡 Swagger UI and ReDoc are two popular interfaces for visualizing and interacting with OpenAPI specs.</em></blockquote><p><strong>TO SETUP AND USE SWAGGER</strong></p><p>You need these two main libraries</p><p>✅ 1. swagger-models library</p><h4>📌 Purpose:</h4><p>This is a <strong>core Swagger library</strong> that provides the model classes used to represent the <strong>OpenAPI/Swagger specification</strong> (v3).</p><h4>📦 It includes:</h4><ul><li>Classes like OpenAPI, Info, PathItem, Schema, etc.</li><li>These are used to <strong>build, read, or manipulate</strong> OpenAPI specs programmatically (for example, if you’re building tools or need to customize the OpenAPI JSON manually).</li></ul><h4>📌 Usage:</h4><ul><li>Needed if you’re working with Swagger annotations or building OpenAPI definitions programmatically.</li><li>Often a <strong>transitive dependency</strong>, but you can include it directly for explicit control.</li></ul><h3>✅ 2. springdoc-openapi-starter-webmvc-ui</h3><p>This is the <strong>main dependency</strong> that integrates Spring Boot (Web MVC) with <strong>Springdoc OpenAPI</strong> and <strong>Adds the Swagger UI frontend by doing the following:</strong></p><ul><li>Automatically generate OpenAPI 3 documentation from your Spring Boot controllers and annotations</li><li>Expose endpoints like:</li><li>/v3/api-docs → raw OpenAPI JSON</li><li>/swagger-ui.html → Swagger UI web interface</li><li>/swagger-ui/index.html → actual UI path</li></ul><h4>✅ Features:</h4><ul><li>Parses Spring REST controllers using annotations (@RestController, @GetMapping, etc.)</li><li>Auto-documents your APIs in OpenAPI 3 format</li><li>Adds the Swagger UI frontend</li></ul><h3>✅ Please Note USE springdoc-openapi-starter-webflux-ui INSTEAD if your service is reactive.</h3><p>This guide contains part A and part B. Part A is swagger integration which is followed by Redoc integation.</p><h3>STEP BY STEP SWAGGER AND REDOC INTEGRATION GUIDE</h3><h3>SWAGGER INTEGRATION</h3><ol><li>Locate your pom.xml file for your service and add properties tag to add swagger version and spring doc version</li></ol><pre> &lt;properties&gt;<br>        &lt;java.version&gt;21&lt;/java.version&gt;<br>        &lt;swaggerVersion&gt;2.2.4&lt;/swaggerVersion&gt;<br>        &lt;swaggerSpringdocVersion&gt;2.6.0&lt;/swaggerSpringdocVersion&gt;<br>    &lt;/properties&gt;</pre><figure><img alt="pom xml file" src="https://cdn-images-1.medium.com/max/731/1*onUcpNMGE9KpaD8Ea50ZTg.png" /></figure><p>2. Add the two libraries(dependencies) for swagger. Note how the tag added above helps us change versions on the fly with little changes</p><pre>&lt;dependency&gt;<br>            &lt;groupId&gt;io.swagger.core.v3&lt;/groupId&gt;<br>            &lt;artifactId&gt;swagger-models&lt;/artifactId&gt;<br>            &lt;version&gt;${swaggerVersion}&lt;/version&gt;<br>            &lt;scope&gt;compile&lt;/scope&gt;<br>        &lt;/dependency&gt;<br><br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>            &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>            &lt;version&gt;${swaggerSpringdocVersion}&lt;/version&gt;<br>        &lt;/dependency&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*ARHOcuJahGmn4BH2OvXAdg.png" /><figcaption>swagger core and spring doc dependencies</figcaption></figure><p>3. Reload/Sync pom.xml changes or reload maven project. (Sync new dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*zpcT84drJ7S8uK6k8YjtNQ.png" /><figcaption>reload your maven project</figcaption></figure><p>Create a configuration package and add a bean named SwaggerConfiguraion. Example below</p><pre>/**<br> * This class enables swagger user interface<br> */<br><br>@Configuration<br>public class SwaggerConfiguration {<br>    @Value(&quot;${spring.application.name}&quot;)<br>    public String appName;<br><br>    @Bean<br>    OpenAPI api() {<br>        return new OpenAPI()<br>                .info(new Info()<br>                        .title(appName.toUpperCase())<br>                        .description(&quot;YOUR COMPANY NAME&quot; + &quot; &quot; + appName.toUpperCase())<br>                        .version(&quot;1.0.0&quot;)<br>                        .contact(new Contact()<br>                                .url(https://medium.com/&quot;https://company.com&quot;)<br>                                .email(&quot;info@company.com&quot;)<br>                                .name(&quot;Software company name LTD.&quot;))<br>                ).addSecurityItem(new SecurityRequirement().addList(&quot;ApiKeyAuth&quot;))<br>                .components(new io.swagger.v3.oas.models.Components()<br>                        .addSecuritySchemes(&quot;ApiKeyAuth&quot;,<br>                                new SecurityScheme()<br>                                        .type(SecurityScheme.Type.APIKEY)<br>                                        .in(SecurityScheme.In.HEADER)<br>                                        .name(&quot;Authorization&quot;))<br>                );<br>    }<br>}</pre><p><strong>ABOUT THIS BEAN </strong><br>This SwaggerConfiguration bean class is a Spring configuration class that sets up OpenAPI (Swagger) documentation for your Spring Boot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*NfWKvdzNvlpzbPQqyTPfUQ.png" /><figcaption>Config folder to hold springboot config beans</figcaption></figure><h3>@Configuration</h3><ul><li>Marks this class as a Spring configuration class, meaning it contains bean definitions that Spring will process at startup.</li><li>Spring will create and manage the beans defined here.</li></ul><h3>@Value(&quot;${spring.application.name}&quot;)</h3><ul><li>Injects the value of the property spring.application.name from application.properties or application.yml into the appName field.</li><li>Example: If spring.application.name=books-service, then appName = &quot;books-service&quot;</li></ul><h3>@Bean OpenAPI api()</h3><ul><li>Defines a Spring bean of type OpenAPI, which configures the Swagger/OpenAPI documentation.</li><li>The returned OpenAPI object contains metadata about your API.</li></ul><h3>OpenAPI Configuration Breakdown</h3><h4>1. Adding Basic API Info (info)</h4><pre>.info(new Info()<br>    .title(appName.toUpperCase()) // API title (e.g., &quot;POLICY-SERVICE&quot;)<br>    .description(&quot;COMPANY NAME&quot; + &quot; &quot; + appName.toUpperCase()) // API description<br>    .version(&quot;1.0.0&quot;) // API version<br>    .contact(new Contact()<br>        .url(https://medium.com/&quot;https://companyName.com&quot;) // Company website<br>        .email(&quot;info@companyName.com&quot;) // Support email<br>        .name(&quot;companyName LTD.&quot;) // Company name<br>    )<br>)</pre><ul><li>Sets metadata like title, description, version, and contact information.</li></ul><h4>2. Security Requirement (addSecurityItem)</h4><pre>.addSecurityItem(new SecurityRequirement().addList(&quot;ApiKeyAuth&quot;))</pre><ul><li>Declares that the API requires security (ApiKeyAuth) by default.</li><li>This means all endpoints will be marked as requiring an API key unless explicitly excluded.</li></ul><h4>3. Security Scheme (components)</h4><pre>.components(new Components()<br>    .addSecuritySchemes(&quot;ApiKeyAuth&quot;,<br>        new SecurityScheme()<br>            .type(SecurityScheme.Type.APIKEY) // API Key-based security<br>            .in(SecurityScheme.In.HEADER) // Key is passed in the header<br>            .name(&quot;Authorization&quot;) // Header name<br>    )<br>)</pre><ul><li>Defines how security works (ApiKeyAuth scheme).</li><li>type: APIKEY → Authentication via an API key.</li><li>in: HEADER → The key must be sent in the HTTP header.</li><li>name: &quot;Authorization&quot; → The header key is Authorization.</li></ul><h3>How It Works in Practice</h3><ul><li>When you access /swagger-ui.html, this configuration generates the API documentation.</li><li>All endpoints will require an Authorization header.</li></ul><p>Ensure you add the below application properties file config for swagger to automatically configure its path . You can also choose to set the path yourself.</p><p>Also check yaml equivalent if using yaml.</p><pre><br>springdoc.swagger-ui.use-root-path=true</pre><p>Run your Service and serve swagger e.g at<br><a href="http://localhost:3000/common-service/swagger-ui/index.html">http://localhost:2502/your-service-context-name/swagger-ui/index.html</a></p><p><strong>Format break down</strong></p><p><a href="http://localhost:2502/dp-service/swagger-ui/index.html"><strong>http://localhost:2502/dp-service/swagger-ui/index.html</strong></a></p><p>[<strong>host ip</strong>] <strong>:</strong> [<strong>Service port</strong>]/ <strong>SERVICE CONTEXT PATH</strong>/<a href="http://localhost:3000/common-service/swagger-ui/index.html">swagger-ui/index.html</a></p><p>Please note for mvc services the server port and context are usually defined in your <strong>application properties file.</strong></p><p><strong>Example below:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*8_ZlIY84Cz2URjRzND7Dmg.png" /><figcaption>S</figcaption></figure><h3>REDOC INTEGRATION GUIDE</h3><p>Redoc is among the latest open source projects derived from swagger as of the time of writing this article.</p><p><strong>ReDoc</strong> is a <strong>frontend tool for generating interactive API documentation</strong> from an <strong>OpenAPI (formerly Swagger) specification</strong>.</p><h3>🔍 What ReDoc Does:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNYp9XAB6cMSLdT4RtlkpQ.png" /><figcaption>Redoc in action</figcaption></figure><p>It takes your OpenAPI YAML or JSON file (usually served at /v3/api-docs), and renders a <strong>beautiful, interactive, and responsive</strong> documentation UI in the browser.</p><h3>✅ Key Features of ReDoc:</h3><p>FeatureDescription📘 <strong>OpenAPI 3.x support</strong>Full support for OpenAPI 3.0+ specs.💡 <strong>Interactive UI</strong>Allows you to explore endpoints, parameters, schemas, etc.🧭 <strong>Deep linking</strong>Each section of the documentation can be linked directly via URL.🧩 <strong>Customizable layout</strong>Allows theming, logos, section ordering, and branding.🔒 <strong>Static HTML</strong>Can be bundled into a single HTML page for hosting without a backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kklk9JNxg0Kv5fo1c_2_Kg.png" /><figcaption>Redoc Documentation sample</figcaption></figure><p>To integrate Redoc in your spring boot microservice you need to setup swagger first as above.</p><p>Then,</p><ol><li><strong>Create a controller to serve your swagger specification via Redoc</strong></li></ol><pre>@RestController<br>@RequestMapping(&quot;/api&quot;)<br>@RequiredArgsConstructor<br>@Slf4j<br>public class RedocController {<br><br>    private final ServletContext servletContext;<br><br><br>    @GetMapping(value = &quot;/getRedocDocumentation&quot;,produces = &quot;text/html&quot;)<br>    public String getRedocDocumentation() {<br><br>        String contextPath = servletContext.getContextPath(); // dynamically gets the current context path<br>        String redocUrl = contextPath + &quot;/v3/api-docs&quot;;<br>        log.debug(&quot;contextPath for redoc is: {}&quot;, contextPath);<br>        log.debug(&quot;Redoc Documentation SPEC Url is: {}&quot;, redocUrl);<br><br><br>        return &quot;&lt;!DOCTYPE html&gt;\n&quot; +<br>                &quot;&lt;html&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;head&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;title&gt;API Docs&lt;/title&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;!-- needed for mobile devices --&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1\&quot;&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;/head&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;body&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;redoc spec-url=\&quot;&quot; + redocUrl + &quot;\&quot;&gt;&lt;/redoc&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;script src=\&quot;https://rebilly.github.io/ReDoc/releases/latest/redoc.min.js\&quot;&gt;&lt;/script&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;/body&gt;\n&quot; +<br>                &quot;\n&quot; +<br>                &quot;&lt;/html&gt;&quot;;<br>    }<br>}</pre><p>2. WhiteList the endpoint <strong>/getRedocDocumentation if security is enabled</strong></p><p><strong>ABOUT THE REDOC CONTROLLER</strong></p><p>This RedocController is a Spring Boot REST controller that serves a <strong>ReDoc-powered API documentation page</strong> using an HTML response.</p><h3>🔍 Annotations Overview</h3><ul><li>@RestController:<br> Combines @Controller and @ResponseBody → means this class handles HTTP requests and returns data (like HTML or JSON) <strong>directly in the response body</strong>, not a view name.</li><li>@RequestMapping(&quot;/api&quot;):<br> Prefixes all routes in this controller with /api. So the final path becomes /api/getRedocDocumentation.</li><li>@RequiredArgsConstructor:<br> From Lombok — automatically generates a constructor for all final fields (servletContext in this case), enabling dependency injection.</li><li>@Slf4j:<br> Also from Lombok — provides a log object to write log messages (like log.debug()).</li><li><strong>PLEASE NOTE LOMBOX HAS A DEPENDENCY YOU CAN ADD IT TOO IN YOUR POM XML TO REDUCE BOILER PLATE CODE under dependencies tag</strong></li></ul><pre> &lt;dependency&gt;<br>            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>            &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>            &lt;scope&gt;provided&lt;/scope&gt;<br>        &lt;/dependency&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*yENr5-OIyfDg6AWK-OdVuA.png" /><figcaption>Lombok dependency</figcaption></figure><ul><li>The line Below is a part of an HTML string in your Java method that serves a ReDoc-based documentation page.</li></ul><pre>&quot;&lt;redoc spec-url=\&quot;&quot; + redocUrl + &quot;\&quot;&gt;&lt;/redoc&gt;\n&quot; +</pre><h3>🔍 Breakdown:</h3><ul><li>&lt;redoc&gt; is a <strong>custom HTML tag</strong> used by <strong>ReDoc</strong>, a popular API documentation tool for OpenAPI specs.</li><li>spec-url=&quot;...&quot; is an attribute that tells ReDoc <strong>where to fetch the OpenAPI/Swagger specification</strong> (usually a .json from /v3/api-docs).</li><li>redocUrl is a Java variable holding the URL to your OpenAPI spec endpoint. Its based on context path and swagger v3 api docs path.</li></ul><h3>🧠 What it does:</h3><p>This line dynamically generates the HTML needed to embed ReDoc:</p><pre>&lt;redoc spec-url=&quot;/v3/api-docs&quot;&gt;&lt;/redoc&gt;</pre><p>Which tells the ReDoc script (included via &lt;script src=...&gt;) to fetch the API spec from that URL and render it in the browser.</p><h3>✅ So the whole flow becomes:</h3><ol><li>Java returns an HTML page with a &lt;redoc&gt; element and the OpenAPI spec URL.</li><li>The browser loads ReDoc (redoc.min.js).</li><li>ReDoc reads the OpenAPI JSON from spec-url.</li><li>The documentation is rendered interactively in the browser.</li></ol><p><strong>ACCESSING REDOC WITH OUR ENDPOINT</strong></p><p>Ensure you wait for your service to build and run and come up as well as initialize swagger. Once swagger is up you can check the redoc documentation as well.</p><p><a href="http://localhost:2502/dp-service/api/getRedocDocumentation#">http://localhost:2502/dp-service/api/getRedocDocumentation#</a></p><p><strong>Thank you for reading. Hope this was helpfull. Follow me and clap for more. Dont forget to follow me on youtube.<br></strong><a href="https://www.youtube.com/@TechknowKenya"><strong> youtube.com/@TechknowKenya</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=268218052b67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SLF4J Easily for logging and setting up Customized Logback XML configurations with…]]></title>
            <link>https://medium.com/@robindamisi/understanding-slf4j-easily-for-logging-and-setting-up-customized-logback-xml-configurations-with-6db0ff6d167e?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db0ff6d167e</guid>
            <category><![CDATA[slf4j]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 09:56:29 GMT</pubDate>
            <atom:updated>2025-04-25T09:56:29.547Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding SLF4J Easily for </strong>logging and setting up Customized Logback XML configurations with appenders in a Modern maven based <strong>Spring Boot</strong> application, Step by step, beginner friendly Guide- A MUST READ for All Developers.</h3><figure><img alt="Console logs for a spring boot application" src="https://cdn-images-1.medium.com/max/1024/1*VWHWYC4FDKL0OF_cUeukig.png" /></figure><p><strong>SLF4J</strong> stands for <strong>Simple Logging Facade for Java</strong>. Think of it like a <strong>universal remote</strong> for logging — it lets you use one logging API, but plug in different actual logging backends (like Logback, Log4j2, etc.).</p><p>Spring Boot uses <strong>Logback</strong> by default.</p><h3>Using SLF4J and Its Syntax</h3><p>If SLF4J isn`t added or not enabled by default in your project you could aded the dependency under your pom.xml file</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>  &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br></pre><p>Please note that for modern Spring Boot projects, it’s usually already/ included by default and you may not need to add the above dependency by yourself.</p><p>🔹 Basic Syntax</p><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>public class MyClass {<br><br>    // Create a logger for this class<br>    private static final Logger logger = LoggerFactory.getLogger(MyClass.class);<br><br>    public void doSomething() {<br>        logger.info(&quot;Application started&quot;);<br>        logger.debug(&quot;Debug message&quot;);<br>        logger.warn(&quot;This is a warning&quot;);<br>        logger.error(&quot;Something went wrong: {}&quot;, &quot;error details&quot;);<br>    }<br>}</pre><h3>Parameterized Logging Syntax Explained</h3><p>Use {} placeholders instead of string concatenation:</p><pre>String user = &quot;john&quot;;<br>logger.info(&quot;User {} has logged in&quot;, user);</pre><p>SLF4J supports logging with <strong>multiple variables</strong> on the same line using {} placeholders — one for each value — and it handles them <strong>in order</strong>.</p><p>Example: Logging with 3+ variables</p><pre>String user = &quot;john&quot;;<br>String role = &quot;admin&quot;;<br>int loginCount = 5;<br><br>logger.info(&quot;User: {}, Role: {}, Login count: {}&quot;, user, role, loginCount);</pre><p>Sample Output for the above:</p><p>INFO User: john, Role: admin, Login count: 5</p><h3>💡 Important SLF4J Syntax Notes:</h3><ul><li>Make sure the <strong>number of </strong><strong>{} matches</strong> the number of arguments.</li><li>If you mismatch (e.g., too few placeholders or too many arguments), it may ignore extras or throw a formatting error in some edge cases.</li><li>❌ Incorrect example:</li></ul><pre>logger.info(&quot;User: {}, Role: {}&quot;, user, role, loginCount);  // Too many args-This is incorrect </pre><p>✅ Fix:</p><pre>logger.info(&quot;User: {}, Role: {}, Login count: {}&quot;, user, role, loginCount);</pre><h3>Logging Exceptions</h3><pre>try {<br>    int result = 10 / 0;<br>} catch (Exception e) {<br>    logger.error(&quot;An error occurred: {}&quot;, e.getMessage(), e);<br>}</pre><p>The third parameter (e) prints the full stack trace.</p><p><strong>Please note</strong> that you can pass <strong>more arguments than </strong><strong>{} placeholders</strong> in SLF4J when logging exceptions. This is only allowed for exceptions as SLF4J has an inbuilt behavior whereby its able to interpret throwables — like in this example below:</p><pre>logger.error(&quot;Error for user: {}, role: {}, reason: {}&quot;, user, role, e.getMessage(), e);</pre><pre>String user = &quot;john&quot;;<br>String role = &quot;admin&quot;;<br><br>try {<br>    int result = 10 / 0;<br>} catch (Exception e) {<br>    logger.error(&quot;Error for user: {}, role: {}, reason: {}&quot;, user, role, e.getMessage(), e);<br>}</pre><p><strong>Sample Output:</strong></p><pre>ERROR Error for user: john, role: admin, reason: / by zero<br>java.lang.ArithmeticException: / by zero<br>    at com.example.MyClass.someMethod(MyClass.java:25)<br>    ...</pre><p>In the above we are passing <strong>4 arguments</strong> (user, role, e.getMessage(), e) but only <strong>3 placeholders</strong> {}. This causes SLF4J to interpret the <strong>last argument (</strong><strong>e) as a </strong><strong>Throwable</strong> — which is exactly what it expects <strong>if you&#39;re logging an exception</strong>.</p><h3>🔸 Logging Best Practices</h3><ul><li>Always define logger <strong>per class</strong></li><li>Avoid System.out.println() in real apps — use logger.info(), etc.</li><li>Prefer placeholders ({}) over concatenation (+)</li><li>Use appropriate levels:</li><li>trace → very fine-grained</li><li>debug → developer-level</li><li>info → normal app messages</li><li>warn → something unexpected, but not broken</li><li>error → something failed</li></ul><h3>How Logging Works in Spring Boot</h3><ul><li>Spring Boot uses SLF4J as the API.</li><li>Under the hood, it uses <strong>Logback</strong> as the default logging implementation.</li></ul><p>So, when you write this:</p><pre>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>Logger logger = LoggerFactory.getLogger(MyClass.class);<br>logger.info(&quot;Hello Logging!&quot;);</pre><p>It <strong>routes</strong> to Logback (by default) to actually do the logging.</p><p><strong>So Where does the</strong><strong>.xml come in?</strong></p><p>The <strong>logback.xml</strong> file is used to <strong>configure</strong> Logback’s behavior. You can:</p><ul><li>Set the log level (INFO, DEBUG, etc.)</li><li>Define where logs should go (file, console, etc.)</li><li>Format how logs look</li><li>Define filters or conditions</li></ul><p>A sample logback xml file would look as follows</p><figure><img alt="Sample screenshot of Logback xml file configuration for SLF4J" src="https://cdn-images-1.medium.com/max/1024/1*yO-bLenbjhljeAqL2_2csg.png" /></figure><p>How to Create a logback.xml file</p><p>Under resources folder create an xml file named logback and Place the file accordingly:</p><p>A simple logback.xml looks like this:</p><pre>&lt;configuration&gt;<br><br>    &lt;!-- Console Appender: logs to the console --&gt;<br>    &lt;appender name=&quot;CONSOLE&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;<br>        &lt;encoder&gt;<br>            &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n&lt;/pattern&gt;<br>        &lt;/encoder&gt;<br>    &lt;/appender&gt;<br><br>    &lt;!-- File Appender: logs to a file --&gt;<br>    &lt;appender name=&quot;FILE&quot; class=&quot;ch.qos.logback.core.FileAppender&quot;&gt;<br>        &lt;file&gt;logs/app.log&lt;/file&gt;<br>        &lt;append&gt;true&lt;/append&gt;<br>        &lt;encoder&gt;<br>            &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:ss} - %logger{36} - %msg%n&lt;/pattern&gt;<br>        &lt;/encoder&gt;<br>    &lt;/appender&gt;<br><br>    &lt;!-- Root Logger Configuration --&gt;<br>    &lt;root level=&quot;INFO&quot;&gt;<br>        &lt;appender-ref ref=&quot;CONSOLE&quot; /&gt;<br>        &lt;appender-ref ref=&quot;FILE&quot; /&gt;<br>    &lt;/root&gt;<br><br>&lt;/configuration&gt;</pre><h3>What are Appenders?</h3><p><strong>Appenders</strong> define where the log messages go.</p><ul><li>ConsoleAppender: prints logs to the terminal</li><li>FileAppender: writes logs to a file</li><li>You can also use RollingFileAppender (rotates logs) or SMTPAppender (sends logs via email)</li></ul><h3>Log Levels</h3><p>These are used to <strong>filter logs</strong> by importance:</p><ul><li>ERROR: serious issues</li><li>WARN: warning, but app can still run</li><li>INFO: normal operations</li><li>DEBUG: useful for debugging</li><li>TRACE: very detailed logs</li></ul><p>You set this like:</p><pre>&lt;root level=&quot;INFO&quot;&gt;</pre><p>Or for a specific package:</p><pre>&lt;logger name=&quot;com.myapp.service&quot; level=&quot;DEBUG&quot; /&gt;</pre><h3>Spring Boot application.properties (as an alternative configs to the xml configuration)</h3><p>You can also set basic logging settings in theapplication.properties:</p><pre>logging.level.root=INFO<br>logging.level.com.myapp=DEBUG<br>logging.file.name=app.log<br>logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pre><p>But this approach is limited compared to logback.xml.</p><p>8. <strong>Why use </strong><strong>logback.xml?</strong></p><ul><li>More <strong>advanced control</strong></li><li>Conditional logging</li><li>Custom format and filters</li><li>Multiple appenders (e.g., one file for error logs, one for debug logs)</li></ul><p><strong>Summary of Flow</strong></p><pre>Your Java code<br>     ↓<br>SLF4J API<br>     ↓<br>Logback (implementation)<br>     ↓<br>Reads logback.xml<br>     ↓<br>Applies configuration:<br>  ├── Appenders (where to log)<br>  ├── Formatters (how to log)<br>  └── Log Levels (what to log)</pre><h3>Detailed Explanation Step by Step</h3><h3>What Is ConsoleAppender?</h3><p>This class is a <strong>built-in appender</strong> in Logback that:</p><ul><li>Writes logs to the console</li><li>Typically used during development or in containers</li><li>Often included by default in Spring Boot</li></ul><p>Example config:</p><pre>&lt;appender name=&quot;STDOUT&quot; class=&quot;ch.qos.logback.core.ConsoleAppender&quot;&gt;<br>    &lt;encoder&gt;<br>        &lt;pattern&gt;%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n&lt;/pattern&gt;<br>    &lt;/encoder&gt;<br>&lt;/appender&gt;</pre><h3>What Does This Do?</h3><p>It says:<br> ➡️ “Create a console log appender using the ConsoleAppender class from Logback’s core module.”</p><p>🎯 Summary</p><p>ch.qos.logback -Package namespace of the Logback project</p><p>core -The core functionality module of Logback</p><p>ConsoleAppender -Java class that writes log output to the system console</p><h3>🧩 Breaking Down the Class Name</h3><h3>ch.qos.logback.core.ConsoleAppender</h3><p>This is a <strong>fully qualified class name</strong>, made up of:</p><p>ch<strong>Country code</strong> (CH = Switzerland) — where the original developers were based</p><p>qos<strong>Quality Object Systems</strong> — the company that created Logback</p><p>logbackThe <strong>logging framework</strong> (replacement for Log4j)</p><p>coreThe <strong>core module</strong> of Logback (shared by all other parts)</p><p>ConsoleAppenderThe class that handles <strong>writing logs to the console</strong> (stdout or stderr)</p><p>If you’re curious, there are other similar appenders too:</p><ul><li>FileAppender – writes to a file</li><li>RollingFileAppender – writes and rotates log files</li><li>SocketAppender – sends logs over the network</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db0ff6d167e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding everything about spring boot Application Dot properties file, Active profiles and How…]]></title>
            <link>https://medium.com/@robindamisi/understanding-everything-about-spring-boot-application-dot-properties-file-active-profiles-and-how-d1b9c9338978?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1b9c9338978</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[application-properties]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 22:37:25 GMT</pubDate>
            <atom:updated>2025-01-17T22:37:25.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding everything about spring boot Application Dot properties file, Active profiles and How they are used</h3><p>The application.properties file in Spring Boot is a central place where configuration settings for your application are defined.</p><p>These properties control various aspects of the application, such as database connection details, server port, logging levels, and more.</p><p>It provides a convenient way to manage configuration without hardcoding values in your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dnu2bV_W9ecto-VRvQvR7Q.png" /></figure><h3>Key Features of application.properties</h3><ol><li><strong>Centralized Configuration</strong>: All configurations can be managed in one place.</li><li><strong>Profiles Support</strong>: Allows defining environment-specific configurations (e.g., development, testing, production).</li><li><strong>Dynamic Resolution</strong>: You can reference placeholders and use Spring’s property resolution mechanism.</li><li><strong>Override Defaults</strong>: You can override Spring Boot’s default properties.</li></ol><h3>Commonly Used Properties</h3><h4>1. Server Configuration</h4><ul><li>Specify the server port and context path</li></ul><pre>server.port=8080<br>server.servlet.context-path=/myapp</pre><h4>2. Database Configuration</h4><ul><li>Configure the datasource for your application:</li></ul><pre>spring.datasource.url=jdbc:mysql://localhost:3306/mydb<br>spring.datasource.username=root<br>spring.datasource.password=rootpassword<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true</pre><h4>3. Logging Configuration</h4><ul><li>Set the logging levels</li></ul><pre>logging.level.root=INFO<br>logging.level.org.springframework=DEBUG<br>logging.file.name=application.log</pre><h4>4. Spring Profiles</h4><ul><li>Define active profiles for the application:</li></ul><pre>spring.profiles.active=dev</pre><h4>5. Custom Properties</h4><ul><li>Define your custom properties</li></ul><pre>myapp.feature.enabled=true<br>myapp.api.base-url=https://api.example.com</pre><p><strong>HOW THEY ARE USED</strong></p><h3>Accessing Properties in Code</h3><h4>1. Using @Value Annotation</h4><p>You can inject property values directly into your code:</p><pre>@Value(&quot;${myapp.feature.enabled}&quot;)<br>private boolean featureEnabled;<br><br>@Value(&quot;${myapp.api.base-url}&quot;)<br>private String apiBaseUrl;</pre><h4>2. Using @ConfigurationProperties</h4><p>This binds a set of related properties to a POJO:</p><pre>@ConfigurationProperties(prefix = &quot;myapp&quot;)<br>@Component<br>public class MyAppProperties {<br>    private boolean featureEnabled;<br>    private String apiBaseUrl;<br>    // Getters and setters<br>}</pre><pre>@Autowired<br>private MyAppProperties myAppProperties;</pre><h3>Best Practices</h3><ol><li><strong>Use Profiles</strong>: Always separate environment-specific configurations using profiles.</li><li><strong>Keep Secrets Secure</strong>: Avoid hardcoding sensitive information. Use environment variables or external configuration tools like Spring Cloud Config or AWS Parameter Store. (IN MY CASE I HAVE HARD CODED FOR LEARNING PURPORSES)</li><li><strong>Use Default Values</strong>: Provide fallback values using : in property placeholders:</li></ol><pre>@Value(&quot;${myapp.timeout:5000}&quot;)<br>private int timeout;</pre><p><strong>4. Organize Properties</strong>: Group related configurations using prefixes (e.g., myapp.database.url).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1b9c9338978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add new Maven projects to your existing old projects in Intellij Using Spring initializer (…]]></title>
            <link>https://medium.com/@robindamisi/how-to-add-new-maven-projects-to-your-existing-old-projects-in-intellij-using-spring-initializer-b8b51ce6b6a0?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b51ce6b6a0</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-initializr]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 22:13:52 GMT</pubDate>
            <atom:updated>2025-01-17T22:13:52.932Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to add new maven projects to your existing old project in Intellij Using Spring initializer ( java: package org.springframework.boot does not exist fix)</h3><p>Download your project dependences from Spring initializer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CZw34QhVE65xHZemp24oA.png" /></figure><p><strong>Then click Generate to Download project zip template</strong></p><p>Open your project location and place the zip there, then extract the zip using extract here for windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1Orgn2UY12ON6EXm2xZSg.png" /></figure><p>After extracting you can delete the zip and remain with the extracted folder as shown above.</p><p><strong>PLEASE BE CAREFUL NOT TO DELETE EXISTING PROJECT FILES</strong></p><p>Then close the File explorer window and open Intellij</p><p>Click file then&gt;&gt; Open &gt;&gt;Then wait for all project dependencies to be loaded and downloaded</p><p>Viola we are almost there</p><p>Build the project to ensure it runs successfully</p><p>Add some configs in your project</p><pre>spring.application.name=commons-service<br><br>server.servlet.context-path=/commons-service<br><br>server.port=8000<br><br>eventService.url=http://COMMONSSERVICE<br>#feign.common.url=common-api<br>eureka.client.registerWithEureka=true<br>eureka.client.fetchRegistry=true<br><br>spring.datasource.url=jdbc:mysql://localhost:3306/EVENTS_DB<br>spring.datasource.username=Myusername<br>spring.datasource.password=Mypassword<br><br>eureka.client.service-url.defaultZone=http://localhost:9978/eureka<br><br>spring.jpa.hibernate.ddl-auto=update<br><br>#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br>spring.jpa.properties.hibernate.batch_fetch_style=PADDED<br>spring.jpa.properties.hibernate.default_batch_fetch_size=25<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.format_sql=false<br>spring.jpa.properties.hibernate.jdbc.batch_size=20<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueaOA3sK9_fm99nmQ4xt_Q.png" /></figure><p>Now the final bit is to ensure the project is added among your existing projects.</p><p>So click the pom.xml file of the new project&gt;&gt;&gt; Then Right click the file&gt;&gt;&gt; Then click &gt;&gt;&gt;Add as maven project &gt;&gt;&gt;Your project will be now added successfully to the existing old project.</p><p>sample pom.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br> xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br> &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br> &lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;3.4.1&lt;/version&gt;<br>  &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;com.events&lt;/groupId&gt;<br> &lt;artifactId&gt;commons&lt;/artifactId&gt;<br> &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;<br> &lt;name&gt;commons&lt;/name&gt;<br> &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;<br> &lt;url/&gt;<br> &lt;licenses&gt;<br>  &lt;license/&gt;<br> &lt;/licenses&gt;<br> &lt;developers&gt;<br>  &lt;developer/&gt;<br> &lt;/developers&gt;<br> &lt;scm&gt;<br>  &lt;connection/&gt;<br>  &lt;developerConnection/&gt;<br>  &lt;tag/&gt;<br>  &lt;url/&gt;<br> &lt;/scm&gt;<br> &lt;properties&gt;<br>  &lt;java.version&gt;21&lt;/java.version&gt;<br>  &lt;spring-ai.version&gt;1.0.0-M4&lt;/spring-ai.version&gt;<br>  &lt;spring-cloud.version&gt;2024.0.0&lt;/spring-cloud.version&gt;<br> &lt;/properties&gt;<br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-ai-pdf-document-reader&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>   &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;<br> &lt;dependencyManagement&gt;<br>  &lt;dependencies&gt;<br>   &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>    &lt;version&gt;${spring-cloud.version}&lt;/version&gt;<br>    &lt;type&gt;pom&lt;/type&gt;<br>    &lt;scope&gt;import&lt;/scope&gt;<br>   &lt;/dependency&gt;<br>   &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-bom&lt;/artifactId&gt;<br>    &lt;version&gt;${spring-ai.version}&lt;/version&gt;<br>    &lt;type&gt;pom&lt;/type&gt;<br>    &lt;scope&gt;import&lt;/scope&gt;<br>   &lt;/dependency&gt;<br>  &lt;/dependencies&gt;<br> &lt;/dependencyManagement&gt;<br><br> &lt;build&gt;<br>  &lt;plugins&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;annotationProcessorPaths&gt;<br>      &lt;path&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/path&gt;<br>     &lt;/annotationProcessorPaths&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>   &lt;plugin&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;configuration&gt;<br>     &lt;excludes&gt;<br>      &lt;exclude&gt;<br>       &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>       &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>      &lt;/exclude&gt;<br>     &lt;/excludes&gt;<br>    &lt;/configuration&gt;<br>   &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br> &lt;/build&gt;<br> &lt;repositories&gt;<br>  &lt;repository&gt;<br>   &lt;id&gt;spring-milestones&lt;/id&gt;<br>   &lt;name&gt;Spring Milestones&lt;/name&gt;<br>   &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;<br>   &lt;snapshots&gt;<br>    &lt;enabled&gt;false&lt;/enabled&gt;<br>   &lt;/snapshots&gt;<br>  &lt;/repository&gt;<br> &lt;/repositories&gt;<br><br>&lt;/project&gt;</pre><p>Hope this helps you fix the</p><pre>java: package org.springframework.boot does not exist</pre><p>The project is now successfully added to the old project as you can see from the 5 red folders on your right side pane of maven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xwGkcSqD1vNHP_XFeVMrw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b51ce6b6a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolved springframework http converter — HttpMessageNotWritableException: Could not write JSON…]]></title>
            <link>https://medium.com/@robindamisi/resolved-springframework-http-converter-httpmessagenotwritableexception-could-not-write-json-45e675dedd35?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/45e675dedd35</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[springboot-3]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 07:38:52 GMT</pubDate>
            <atom:updated>2024-10-13T07:38:52.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Resolved springframework http converter — HttpMessageNotWritableException: Could not write JSON Because Document nesting depth (1001) exceeds the maximum allowed (1000, from `StreamWriteConstraints.getMaxNestingDepth()`)]</h3><pre>Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could<br> not write JSON: Document nesting depth (1001) exceeds the maximum allowed (1000, from `StreamWriteConstraints.getMaxNestingDepth()`)]</pre><p>Ensure you add @JsonManagedReference annotation</p><figure><img alt="Document nesting depth (1001) exceeds the maximum allowed recursion exception in spring boot" src="https://cdn-images-1.medium.com/max/1024/1*BIOymFw4-udeVeKGEnDTpQ.png" /></figure><p>The @JsonManagedReference annotation is used in the context of serializing and deserializing JSON in a parent-child relationship, specifically with Jackson, a popular JSON library in Java and Kotlin. It helps resolve issues that can arise from bi-directional relationships during the JSON serialization process.</p><p>Here’s what @JsonManagedReference does:</p><h3>1. Bi-directional Relationship and Infinite Recursion</h3><p>In a typical bi-directional relationship between entities (like Client and Policy), both the parent and child entities reference each other. For example:</p><pre>data class Client(<br>    @JsonManagedReference<br>    var policy: MutableList&lt;Policy&gt;? = null<br>)<br><br>data class Policy(<br>    @JsonBackReference<br>    var client: Client? = null<br>)</pre><ul><li>The Client entity has a list of Policy objects.</li><li>Each Policy object references back to its Client.</li></ul><p>When Jackson tries to serialize this relationship into JSON, it may run into <strong>infinite recursion</strong>:</p><ul><li>It will serialize Client and try to serialize the list of Policy.</li><li>When serializing each Policy, it will also serialize its Client reference, which in turn contains a list of Policy, causing an endless loop.</li></ul><h3>2. How @JsonManagedReference and @JsonBackReference Work</h3><ul><li>@JsonManagedReference: Applied to the <strong>parent</strong> side of the relationship (e.g., Client), this marks the property that holds the reference to the child entities (e.g., the list of Policy).</li><li>@JsonBackReference: Applied to the <strong>child</strong> side of the relationship (e.g., Policy), it prevents the serialization of the back reference (the parent) to break the potential infinite loop.</li></ul><h4>Example:</h4><pre>data class Client(<br>    @JsonManagedReference<br>    var policy: MutableList&lt;Policy&gt;? = null<br>)<br><br>data class Policy(<br>    @JsonBackReference<br>    var client: Client? = null<br>)</pre><p>In this case:</p><ul><li>When serializing a Client object, Jackson will include the policy list in the output.</li><li>When serializing a Policy object as part of that list, it will <strong>not</strong> include the client reference (the parent).</li></ul><p>This breaks the cycle and prevents infinite recursion.</p><h3>3. Deserialization</h3><ul><li>During <strong>deserialization</strong>, the @JsonManagedReference and @JsonBackReference annotations work together to ensure that the relationship is properly restored. Jackson will link the parent and child entities correctly.</li></ul><h3>Use Case for var policy: MutableList&lt;Policy&gt;? = null</h3><p>In our example:</p><pre>@JsonManagedReference<br>var policy: MutableList&lt;Policy&gt;? = null</pre><p>This means that:</p><ul><li>policy holds the child entities (Policy) in the Client entity.</li><li>When serializing Client, Jackson will serialize the policy list.</li><li>However, during the serialization of Policy, the client reference won&#39;t be included in the JSON to avoid the recursion issue.</li></ul><h3>When to Use It</h3><p>Use @JsonManagedReference and @JsonBackReference when you have bi-directional relationships between entities and you&#39;re serializing them to JSON using Jackson, especially when you want to avoid infinite loops during serialization.</p><p>Thank you for reading, Follow &amp; subcribe to my youtube channel. youtube.com/@TechknowKenya</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45e675dedd35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring a Spring Data source in your application.properties file for Mysql Springboot]]></title>
            <link>https://medium.com/@robindamisi/configuring-a-spring-data-source-in-your-application-properties-file-for-mysql-springboot-c70c67fe509b?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70c67fe509b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[application-properties]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 11:17:34 GMT</pubDate>
            <atom:updated>2024-09-08T11:17:34.426Z</atom:updated>
            <content:encoded><![CDATA[<p>This example includes settings for connecting to a MySQL database</p><pre># Database connection settings<br>spring.datasource.url=jdbc:mysql://localhost:3306/my_database?useSSL=false&amp;serverTimezone=UTC<br>spring.datasource.username=my_username<br>spring.datasource.password=my_password</pre><pre># Connection pool settings (optional, but recommended)<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br>spring.datasource.initialization-mode=always<br># HikariCP connection pool settings (if using HikariCP)<br>spring.datasource.hikari.connection-timeout=20000<br>spring.datasource.hikari.maximum-pool-size=10<br>spring.datasource.hikari.minimum-idle=5<br>spring.datasource.hikari.idle-timeout=300000<br>spring.datasource.hikari.max-lifetime=1800000<br># JPA settings (optional for Spring Data JPA)<br>spring.jpa.show-sql=true<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect<br># Logging SQL Queries<br>logging.level.org.hibernate.SQL=DEBUG<br>logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE</pre><h3>Explanation:</h3><ul><li>spring.datasource.url: Specifies the JDBC URL of the database.</li><li>spring.datasource.username &amp; spring.datasource.password: Credentials for the database.</li><li>spring.datasource.driver-class-name: Driver class for MySQL.</li><li>HikariCP settings are included to fine-tune the connection pool (you can adjust them based on your needs).</li><li>spring.jpa.hibernate.ddl-auto: Defines the database schema creation/update strategy (update, create, validate, etc.).</li><li>spring.jpa.show-sql: Enables logging of SQL statements.</li><li>logging.level: Configures logging for SQL and SQL bind parameters.</li></ul><pre>spring.jpa.properties.hibernate.batch_fetch_style=PADDED <br>spring.jpa.properties.hibernate.default_batch_fetch_size=25 <br>spring.jpa.show-sql=true <br>spring.jpa.properties.hibernate.format_sql=false <br>spring.jpa.properties.hibernate.jdbc.batch_size=20</pre><p><strong>what does these do</strong></p><p>Let’s break down each of these Spring JPA and Hibernate properties to understand what they do:</p><h3>1.spring.jpa.properties.hibernate.batch_fetch_style=PADDED</h3><p>This property configures the <strong>batch fetching style</strong> in Hibernate:</p><ul><li><strong>PADDED</strong>: When batch fetching entities, this setting tells Hibernate to pad the number of fetched records to the nearest multiple of the batch size. For example, if the batch size is set to 25, but there are only 18 records to fetch, Hibernate will pad it to 25 by fetching extra dummy records. This helps in cases where consistent batch sizes can improve performance, but padding ensures that the batch size is always uniform.</li></ul><h3>2. spring.jpa.properties.hibernate.default_batch_fetch_size=25</h3><p>This property configures the <strong>batch fetching size</strong>:</p><ul><li><strong>Batch fetching</strong> is a way to optimize fetching of related entities by retrieving them in batches instead of one-by-one. When Hibernate fetches related entities (like collections or associations), it will fetch them in batches of 25. This reduces the number of database round-trips and can improve performance significantly when dealing with large datasets.</li></ul><h3>3. spring.jpa.show-sql=true</h3><p>This property enables the <strong>logging of SQL statements</strong> executed by Hibernate:</p><ul><li>When set to true, it will log all the SQL queries that Hibernate generates and sends to the database. This is useful for debugging and monitoring what queries are being executed.</li></ul><h3>4. spring.jpa.properties.hibernate.format_sql=false</h3><p>This property configures the formatting of the SQL output in logs:</p><ul><li>When set to false, Hibernate will print the SQL queries in a single line (without formatting), which can save space in logs.</li><li>If set to true, it will format the SQL queries to make them easier to read by adding line breaks and indentation.</li></ul><h3>5. spring.jpa.properties.hibernate.jdbc.batch_size=20</h3><p>This property configures <strong>JDBC batch processing</strong> in Hibernate:</p><ul><li><strong>Batch processing</strong> refers to sending multiple SQL statements to the database in a single network call, which can reduce the time spent on database communication.</li><li>Setting this value to 20 means that Hibernate will batch 20 insert/update/delete statements together before sending them to the database in one go, rather than sending them one by one. This can improve performance when dealing with a large number of database writes.</li></ul><h3>Summary</h3><ul><li><strong>batch_fetch_style=PADDED</strong>: Ensures that fetched entities are padded to the batch size.</li><li><strong>default_batch_fetch_size=25</strong>: Hibernate will batch fetch 25 entities at a time to reduce database round-trips.</li><li><strong>show-sql=true</strong>: Enables logging of SQL queries for easier debugging.</li><li><strong>format_sql=false</strong>: Disables formatting of the SQL queries in logs to save space.</li><li><strong>jdbc.batch_size=20</strong>: Groups 20 SQL write operations (like inserts/updates/deletes) in one batch to reduce database communication and improve performance.</li></ul><p>These settings are primarily aimed at improving the performance of your application by batching database operations and controlling how SQL queries are logged and fetched.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70c67fe509b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error creating bean with name ‘clientRepository’ defined in com.Repository]]></title>
            <link>https://medium.com/@robindamisi/error-creating-bean-with-name-clientrepository-defined-in-com-repository-ca8562803440?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8562803440</guid>
            <category><![CDATA[error]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 11:09:47 GMT</pubDate>
            <atom:updated>2024-09-08T11:09:47.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error creating bean with name ‘clientRepository’ defined in com.Repository defined in <a href="http://twitter.com/EnableJpaRepositorie">@EnableJpaRepositorie</a>s declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: kotlin/reflect/full/KClasses Fix</h3><p>This indicates an issue related to Kotlin reflection (kotlin.reflect.full.KClasses) and the creation of the clientRepository bean in your Spring Data JPA setup.</p><p>This issue can arise from various causes. Here are potential solutions:</p><h3>1. Add Kotlin Reflection Dependency</h3><p>The error mentions kotlin.reflect.full.KClasses, which suggests that the project is missing the Kotlin reflection library. Spring Data JPA requires Kotlin reflection for some operations, like working with entity classes and repositories.</p><p><strong>Solution</strong>: Add the kotlin-reflect dependency to your build.gradle (if you&#39;re using Gradle) or pom.xml (if you&#39;re using Maven).</p><ul><li>For <strong>Gradle</strong>: groovy</li></ul><pre>dependencies {     implementation &quot;org.jetbrains.kotlin:kotlin-reflect&quot; }</pre><p>For maven</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.jetbrains.kotlin&lt;/groupId&gt;<br>    &lt;artifactId&gt;kotlin-reflect&lt;/artifactId&gt;<br>    &lt;version&gt;${kotlin.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>2. Repository Interface</h3><p>Ensure that the ClientRepository interface extends the correct Spring Data JPA repository interface.</p><p>For example:</p><pre>package com.attendees.attendees.repository</pre><pre>import com.attendees.attendees.model.Client<br>import org.springframework.data.jpa.repository.JpaRepository</pre><pre>interface ClientRepository : JpaRepository&lt;Client, Long&gt; {<br>}</pre><p>Make sure that:</p><ul><li>The entity class (Client) is correctly defined and annotated with @Entity.</li><li>The ClientRepository extends from JpaRepository or another correct Spring Data repository interface.</li></ul><h3>3. Ensure Proper Entity Configuration</h3><p>Verify that your entity classes are properly annotated and have all the necessary configurations:</p><pre>@Entity<br>@Table(name = &quot;client&quot;)<br>data class Client(<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    val id: Long,<br>    val name: String,<br>    // other fields<br>)</pre><h3>4. Check Spring Boot Version and Compatibility</h3><p>Ensure that you’re using a compatible version of Spring Boot with Kotlin. If you’re using older versions of Spring Boot or Kotlin, compatibility issues might arise.</p><ul><li>Check your spring-boot-starter-data-jpa version.</li><li>Ensure that you’re using the right Kotlin version by verifying your build.gradle or pom.xml.</li></ul><h3>5. Check @EnableJpaRepositories Configuration</h3><p>Ensure that the @EnableJpaRepositories annotation (if used) is configured properly. In most cases, Spring Boot auto-configures this, so you don&#39;t need to manually declare it.</p><p>If you manually declared @EnableJpaRepositories, ensure that the basePackages attribute points to the correct package where your repositories are defined:</p><pre>@EnableJpaRepositories(basePackages = [&quot;com.attendees.attendees.repository&quot;])</pre><h3>6. Clean and Rebuild the Project</h3><p>Sometimes build issues or caching problems in the IDE can cause such errors. Try cleaning and rebuilding your project:</p><ul><li>In <strong>Gradle</strong>: Run ./gradlew clean build.</li><li>In <strong>Maven</strong>: Run mvn clean install.</li></ul><p>If you’re using an IDE like IntelliJ IDEA or Eclipse, you can also try invalidating caches and restarting the IDE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8562803440" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get the current index of the current forEach item when using radioOptions in Android Kotlin…]]></title>
            <link>https://medium.com/@robindamisi/how-to-get-the-current-index-of-the-current-foreach-item-when-using-radiooptions-in-android-kotlin-01a71fe16332?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a71fe16332</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[radiobutton]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Sun, 12 May 2024 15:23:14 GMT</pubDate>
            <atom:updated>2024-05-12T15:23:14.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to get the current index of the current for each item when using radioOptions in Android Kotlin Compose</h3><p>If you want to get the index of each iteration in compose such that you have a predined list of slectable options as text you can achieve as follows in android kotlin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvY2c8bgRcE1q1L0z5o9Pg.png" /></figure><p>declare and initialize variables to hold the options and choies selected by user as below</p><pre>    var radioOptions = listOf(firstInstallmentAmountAsString, annualAmountAsString)<br><br>    var selectedOption by remember { mutableStateOf(radioOptions[0]) }<br><br><br>    var durations= listOf(&quot;6 months&quot;,&quot;a year&quot; )<br>    var selectedDuration by remember { mutableStateOf(durations[0]) }<br><br></pre><p>Now define your radio button functionality with the forEachIndexed function as below. The function is a lamba function that yields the index and choice as the lambda parameters.</p><p>Please ensure that it is contained inside a container like a column</p><pre><br>                    radioOptions.forEachIndexed  {index, choice -&gt;<br>                        Row(modifier = Modifier.padding(0.1.dp)) {<br>                            RadioButton(<br>                                modifier = Modifier.align(Alignment.CenterVertically),<br>                                selected = (choice == selectedOption),<br>                                onClick = { selectedOption = choice<br><br>                                    onUpdateSelectedRadioOptionChoice(choice)<br><br>                                },<br>                                colors = RadioButtonDefaults.colors(<br>                                    selectedColor = colorPrimary<br>                                )<br>                            )<br>                            Text(<br>                                //use the index of selected option to retrieve corresponding value in durations<br>                                //only assign the received choice value if its not null using take if.<br><br>                                text = &quot;Ksh &quot; +( choice?.takeIf { it.isNotEmpty() } ?: &quot;amount is null&quot;)+&quot; for &quot;+durations.get(index),<br>                                style = MaterialTheme.typography.bodyMedium,<br>                                modifier = Modifier<br>                                    .padding(start = 8.dp)<br>                                    .align(Alignment.CenterVertically)<br>                            )<br>                        }<br>                    }</pre><p>Full code should be almost similar to the below</p><pre> Column(modifier = Modifier.padding(top=5.dp)) {<br><br><br>  radioOptions.forEachIndexed  {index, choice -&gt;<br>                        Row(modifier = Modifier.padding(0.1.dp)) {<br>                            RadioButton(<br>                                modifier = Modifier.align(Alignment.CenterVertically),<br>                                selected = (choice == selectedOption),<br>                                onClick = { selectedOption = choice<br><br>                                    onUpdateSelectedRadioOptionChoice(choice)<br><br>                                },<br>                                colors = RadioButtonDefaults.colors(<br>                                    selectedColor = colorPrimary<br>                                )<br>                            )<br>                            Text(<br>                                //use the index of selected option to retrieve corresponding value in durations<br>                                //only assign the received choice value if its not null using take if.<br><br>                                text = &quot;Ksh &quot; +( choice?.takeIf { it.isNotEmpty() } ?: &quot;amount is null&quot;)+&quot; for &quot;+durations.get(index),<br>                                style = MaterialTheme.typography.bodyMedium,<br>                                modifier = Modifier<br>                                    .padding(start = 8.dp)<br>                                    .align(Alignment.CenterVertically)<br>                            )<br>                        }<br>                    }<br><br><br><br><br><br><br><br><br><br>//end of column container<br>        }<br><br><br><br><br><br><br><br><br><br><br><br></pre><p>Note that this is a solution if you were using forEach and did not know how to get the index of the current iterable item.</p><p>In conclusion, In this modified code:</p><ul><li>I replaced forEach with forEachIndexed, which provides the current index along with the item.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a71fe16332" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix ← HTTP FAILED: javax.net.ssl.SSLHandshakeException: Chain validation failed in Android]]></title>
            <link>https://medium.com/@robindamisi/how-to-fix-http-failed-javax-net-ssl-sslhandshakeexception-chain-validation-failed-in-android-4001bec6314c?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4001bec6314c</guid>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[sslhandshakeexception]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Sat, 04 May 2024 14:56:23 GMT</pubDate>
            <atom:updated>2024-05-04T14:56:23.104Z</atom:updated>
            <content:encoded><![CDATA[<p>IF you are facing the ← HTTP FAILED: javax.net.ssl.SSLHandshakeException: Chain validation failed in Android here is one of the solution</p><pre>← HTTP FAILED: javax.net.ssl.SSLHandshakeException: Chain validation failed </pre><p>Solutions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rbur6v19o_3GZ1TsUUSdcg.png" /></figure><ol><li>Contact Admin and request for a renew of the SSL Certificate of your proxy url or base url you are using.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4001bec6314c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Launched Effect in Android Kotlin Jetpack Compose]]></title>
            <link>https://medium.com/@robindamisi/understanding-launched-effect-in-android-kotlin-jetpack-compose-94a8bf396a75?source=rss-a3d688a986e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/94a8bf396a75</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[launchedeffect]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[side-effects]]></category>
            <dc:creator><![CDATA[Robinson Githae]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 20:46:06 GMT</pubDate>
            <atom:updated>2024-02-27T20:46:06.695Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>Launched effects is part of Side effects in Compose.</p><p>In Jetpack Compose, a launched effect is a mechanism provided by the Kotlin coroutines library to perform asynchronous tasks in a Composable function.</p><p>It allows you to execute side effects such as fetching data from a network, performing database operations, or executing any other long-running task without blocking the main UI thread.</p><p>To use a launched effect in your Android app built with Jetpack Compose and Kotlin, you can follow these basic steps:</p><ol><li>Add the necessary dependencies to your project. Ensure that you have the Kotlin coroutines library and Jetpack Compose dependencies set up in your build.gradle file.</li><li>Import the required classes and functions for coroutines and Jetpack Compose in your Kotlin file.</li><li>Inside your Composable function, use the LaunchedEffect composable function to launch a coroutine that performs the desired asynchronous task.</li></ol><p><strong>Example of launched effect in use</strong></p><pre>import androidx.compose.runtime.*<br>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.launch<br><br>@Composable<br>fun MyComposable() {<br>    var data by remember { mutableStateOf(&quot;Loading...&quot;) }<br><br>    LaunchedEffect(true) {<br>        // This coroutine will be launched when MyComposable is initially composed<br>        fetchDataFromNetwork()<br>        data = &quot;Data Loaded&quot;<br>    }<br><br>    Text(text = data)<br>}<br><br>suspend fun fetchDataFromNetwork() {<br>    // Simulate a network request delay<br>    delay(2000)<br>    // Perform actual network request here<br>}</pre><p>In the above example, when MyComposable is initially composed, the LaunchedEffect composable function launches a coroutine using LaunchedEffect(true).</p><p>Inside this coroutine, the fetchDataFromNetwork function is called asynchronously to simulate fetching data from a network. Once the data is fetched (after a delay of 2000 milliseconds in this example), the data variable is updated, triggering recomposition and displaying the loaded data in the UI.</p><p>Remember to handle error cases and cancellation appropriately in your coroutines to ensure the robustness of your app.</p><p>Additionally, you can customize the behavior of LaunchedEffect by providing different keys or dependencies to control when the effect is triggered.</p><p><strong>USING KEYS IN LAUNCHED EFFECT</strong></p><p>In Jetpack Compose, the LaunchedEffect composable function allows you to specify a key parameter to control when the effect should be re-launched.</p><p>This is useful when you want to re-trigger the effect based on changes to specific data or state. Here&#39;s a guide on how to use keys in LaunchedEffect:</p><p><strong>Understanding the Key Parameter:</strong></p><p>The key parameter in LaunchedEffect serves as a unique identifier for the effect.</p><ol><li>When the key changes, the effect will be re-launched. If the key remains the same across recompositions, the effect will not be re-executed.</li><li>Using Keys to Control Re-launching: You can use keys to control when the effect should be re-launched based on changes to certain data or state within your Composable function.</li><li>For example, you may want to re-fetch data from a network only when a specific parameter changes.</li><li>Passing Keys to LaunchedEffect: Pass the key parameter to the LaunchedEffect function to specify when the effect should be re-launched.</li><li>You can use any type that implements equals() and hashCode() as the key. Common types used as keys include strings, integers, or objects with unique identifiers.</li><li>Example Usage:</li></ol><pre>import androidx.compose.runtime.*<br>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.launch<br><br>@Composable<br>fun MyComposable(data: String) {<br>    var result by remember { mutableStateOf(&quot;Loading...&quot;) }<br><br>    LaunchedEffect(data) {<br>        // This coroutine will be launched when the &#39;data&#39; parameter changes<br>        fetchDataFromNetwork(data)<br>        result = &quot;Data Loaded&quot;<br>    }<br><br>    Text(text = result)<br>}<br><br>suspend fun fetchDataFromNetwork(data: String) {<br>    // Simulate a network request delay<br>    delay(2000)<br>    // Perform actual network request using &#39;data&#39;<br>}</pre><p>In the example above, the LaunchedEffect is keyed on the data parameter.</p><p>Whenever the value of data changes, the effect will be re-launched, triggering the asynchronous task of fetching data from the network.</p><p><strong>Note:</strong></p><ol><li>Handling Key Changes: Be cautious when using keys in LaunchedEffect to avoid unintended side effects.</li><li>Ensure that the key accurately reflects the dependencies that determine when the effect should be re-executed.</li></ol><p>By understanding and leveraging keys in LaunchedEffect, you can control the behavior of asynchronous tasks and side effects in your Jetpack Compose components more effectively.</p><p>Thank you for reading, hope this helped. Follow me on X as <strong>@Robindamisi</strong> and on Youtube <strong>TechknowKenya</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a8bf396a75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>