<?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 Augusto Sopelsa Klaic on Medium]]></title>
        <description><![CDATA[Stories by Augusto Sopelsa Klaic on Medium]]></description>
        <link>https://medium.com/@augusto.klaic?source=rss-6b3cdb3a1f05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DC-r_-pBL1B9NJ8TMddpiw.jpeg</url>
            <title>Stories by Augusto Sopelsa Klaic on Medium</title>
            <link>https://medium.com/@augusto.klaic?source=rss-6b3cdb3a1f05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:49:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@augusto.klaic/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[Java Series: AI]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-ai-67aef4657948?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/67aef4657948</guid>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Mon, 18 May 2026 20:10:52 GMT</pubDate>
            <atom:updated>2026-05-18T20:10:52.494Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>AI agents</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXtnVOtNyuKvmEQ1WYW95Q.png" /></figure><p>Let’s talk about AI agents in the Java world! 🤖☕</p><p>Today, AI is clearly here to stay. It has already invaded the daily workflow of many professions, and it’s also part of the everyday life of regular people asking questions to AI or searching for information online.</p><p>When using AI tools, we constantly run into terms like:</p><ul><li><strong>“deploying agent…”</strong></li><li><strong>“agent returned with result…”</strong></li></ul><p>And naturally, some questions may come to mind:</p><ul><li><strong>What exactly are these agents?</strong></li><li><strong>What do they actually do?</strong></li></ul><p>In this article, I’ll explain a bit more about AI agents in the Java ecosystem, and by the end we’ll build a full demo project showing how everything works 🚀</p><p>An AI agent is different from a simple LLM. It’s not just a language model that answers questions. An agent has the capability to reason, plan, and act on top of a problem.</p><p>For example:</p><ul><li>A regular LLM receives a prompt and returns an answer.</li><li>An agent receives an objective. Then it decides:<br> → which tools it should use,<br> → in what order,<br> → how many times,<br> → and only after that it delivers the final result.</li></ul><p>This process happens in cycles called <strong>ReAct</strong> — an acronym for <strong>Reason + Act</strong> 🧠⚡</p><p>This is the foundation of many modern AI agents. The cycle usually alternates between:</p><ul><li><strong>Thought:</strong> internal reasoning about the problem</li><li><strong>Action:</strong> calling a tool to solve part of the problem</li><li><strong>Observation:</strong> evaluating the result returned by the tool</li></ul><p>Each step feeds the next one. If the result from a tool is considered inefficient or incomplete, the reasoning process starts again using the outputs from the previous cycles.</p><p>It almost works like a memory loop focused on solving the problem more effectively 🔄</p><p>This memory characteristic is extremely important because it differentiates an agent from a traditional chatbot.</p><p>An agent can maintain context between conversation turns — and sometimes even across different chat sessions — which makes it fundamental for handling tasks composed of multiple steps.</p><p>That’s what makes agents much more powerful and capable than simple chatbots 💪🤖</p><p>But agents alone don’t do much. The real power of an agent comes from the <strong>tools</strong> it has access to 🔧</p><p>A tool can be basically anything, such as:<br>→ Web searches<br>→ Database queries<br>→ API calls<br>→ Processing or calculation tasks</p><p>These tools are mapped in the code using plain-text descriptions explaining what they do, like in the example below using LangChain4j syntax:</p><pre>@Tool(&quot;This tool is used when the user asks about the weather&quot;)</pre><p>So when the LLM receives a request, it can compare the user’s intention with the tool descriptions and decide whether calling that tool is the correct action for that specific context.</p><p>This is what enables us to build highly customizable agents for different objectives 🚀</p><p>Now that we understand what an AI agent is… let’s code one! 💻🔥</p><p>For this implementation, we’ll use <strong>Spring Boot </strong>as the Java framework, <strong>LangChain4j </strong>to orchestrate agents and tools, <strong>Redis </strong>as the agent’s memory database running inside Docker, and <strong>OpenRouter </strong>to access free LLM models through an API 🤖☕🚀</p><p>Everything used in this project can be found at the <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/ai-agents-basics">project’s page on Github</a>.</p><p>Starting with the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/build.gradle">build.gradle</a>:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.4.5&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.aiagentsbasics&#39;<br>version = &#39;0.0.1&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br><br>    // LangChain4j<br>    implementation platform(&#39;dev.langchain4j:langchain4j-bom:1.0.0-beta2&#39;)<br>    implementation &#39;dev.langchain4j:langchain4j&#39;<br>    implementation &#39;dev.langchain4j:langchain4j-open-ai&#39;<br><br>    // Redis<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-redis&#39;<br>}</pre><p>Very simple, as you can see 😄 We basically have:</p><ul><li>the Spring Boot dependencies to start our server,</li><li>the LangChain4j dependency to work with agent tools and manage LLM integrations,</li><li>and the Redis dependency to connect to the Redis server.</li></ul><p>No surprises here 🚀</p><p>Looking at the next part of the project setup, we have the docker-compose file responsible for creating and starting a Redis server, which will be used as the agent’s memory database 🧠 The Docker script looks like this:</p><pre>services:<br>  redis:<br>    image: redis:alpine<br>    ports:<br>      - &quot;6379:6379&quot;</pre><p>Pretty short and direct — we don’t need any fancy setup here 😄 To run this Docker Compose file, just open the folder where the file is located in your terminal and execute the following command:</p><pre>docker-compose -p redis-notes -f redis-notes-docker-compose.yml up -d</pre><p>Once Docker finishes building the container, you’ll have a fully functional Redis server running and ready to be used as the agent’s memory database 🧠🚀</p><p>To finish the project configuration and get everything ready to start, we still need to configure the application properties responsible for connecting to the databases and external APIs. The <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/resources/application.properties">application.properties</a> file should be like this:</p><pre># OpenRouter<br>openrouter.api-key={YOUR_KEY}<br>openrouter.base-url=https://openrouter.ai/api/v1<br>openrouter.model=openai/gpt-oss-120b:free<br><br># Redis<br>spring.data.redis.host=localhost<br>spring.data.redis.port=6379<br><br># Notes folder<br>notes.path=ai-agents-basics/src/main/resources/notes</pre><p>In the application.properties file, we define the connection to the OpenRouter API and configure which LLM model will be used by the application 🤖</p><p>The Redis connection is also configured here — host and port included — along with the path where our AI agent will store the notes we ask it to save 🧠📝 When running the project, remember to add your personal OpenRouter API token 🔑</p><p>Now that the configuration part is done, let’s move to the fun part: writing some code 💻🚀 We’ll start with the agent configuration class. Take a look at the file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/java/com/augusto/aiagentsbasics/config/AgentConfig.java">AgentConfig.java</a></p><pre>@Configuration<br>public class AgentConfig {<br><br>    @Value(&quot;${openrouter.api-key}&quot;)<br>    private String apiKey;<br><br>    @Value(&quot;${openrouter.base-url}&quot;)<br>    private String baseUrl;<br><br>    @Value(&quot;${openrouter.model}&quot;)<br>    private String model;<br><br>    @Bean<br>    public OpenAiChatModel chatModel() {<br>        return OpenAiChatModel.builder()<br>                .apiKey(apiKey)<br>                .baseUrl(baseUrl)<br>                .modelName(model)<br>                .build();<br>    }<br>}</pre><p>In this configuration file, we create the specific beans that Spring will use to make the AI chat model work ☕⚙️</p><p>The chatModel bean connects to OpenRouter and configures the free LLM model that will be used by the application 🤖</p><p>The controller class will be very simple. We only need a single endpoint to send prompts, commands, and questions to the AI model.</p><p>Let’s take a look at the file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/java/com/augusto/aiagentsbasics/controller/AgentController.java">AgentController.java</a></p><pre>@RestController<br>@RequestMapping(&quot;/agent&quot;)<br>public class AgentController {<br><br>    private final AgentService agentService;<br><br>    public AgentController(AgentService agentService) {<br>        this.agentService = agentService;<br>    }<br><br>    @GetMapping(&quot;/chat&quot;)<br>    public String chat(@RequestParam String message) {<br>        return agentService.chat(message);<br>    }<br>}</pre><p>The controller class communicates directly with the service layer, which contains the actual logic behind the agent’s behavior ⚡🤖</p><p>Let’s take a look at the file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/java/com/augusto/aiagentsbasics/agent/AgentService.java">AgentService.java</a></p><pre>@Service<br>public class AgentService {<br><br>    interface Agent {<br>        String chat(String message);<br>    }<br><br>    private Agent agent;<br><br>    public AgentService(OpenAiChatModel model,<br>                        MemoryTool memoryTool,<br>                        NoteTool noteTool) {<br>        this.agent = AiServices.builder(Agent.class)<br>                .chatLanguageModel(model)<br>                .tools(memoryTool, noteTool)<br>                .chatMemory(MessageWindowChatMemory.withMaxMessages(10))<br>                .build();<br>    }<br><br>    public String chat(String message) {<br>        return agent.chat(message);<br>    }<br>}</pre><p>In the agent service, we use a constructor to inject our beans into the Agent interface, which is an abstraction implemented at runtime by LangChain4j 🤖</p><p>You basically define the contract of the interface, and AiServices.builder() dynamically creates the implementation for you — pretty similar to how Spring Data JPA automatically generates repository implementations, but now for AI services 😄</p><p>In our case, the service simply receives a String containing the user’s question and returns another String containing the AI-generated response.</p><p>Another interesting part of this agent constructor is that we define the tool library the AI can use 🔧 If you look at the tools() builder method, you’ll notice that we are registering two tools the AI will use in our system:</p><ul><li>the Memory Tool,</li><li>and the Note Tool.</li></ul><p>We’ll explain both right after this section 🧠📝</p><p>We also configure the chatMemory() method. As the name already suggests, it tells the LLM to remember the last ten messages, creating a conversational memory window between interactions.</p><p>Now that we’ve already seen the backbone of the project, let’s move to the cool part: creating tools for the AI model 🚀 In this project, we’ll have two main tool classes — the Memory Tool and the Note Tool.</p><p>Take a look at the file <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/java/com/augusto/aiagentsbasics/tools/MemoryTool.java">MemoryTool.java</a> first:</p><pre>@Component<br>public class MemoryTool {<br><br>    private final StringRedisTemplate redis;<br><br>    public MemoryTool(StringRedisTemplate redis) {<br>        this.redis = redis;<br>    }<br><br>    @Tool(&quot;Save information in memory to remember later. Use when user asks for remembering something.&quot;)<br>    public String saveInMemory(String key, String value) {<br>        redis.opsForValue().set(key,value);<br>        return &quot;Information saved sucessfully! Key: &quot; + key;<br>    }<br><br>    @Tool(&quot;Search one information saved in memory. Use when user asks for something that were saved before.&quot;)<br>    public String loadFromMemory(String key) {<br>        String value = redis.opsForValue().get(key);<br><br>        if (value == null) {<br>            return &quot;None information were found for key: &quot; + key;<br>        }<br><br>        return &quot;Information found - &quot; + key + &quot;: &quot;  + value;<br>    }<br><br>    @Tool(&quot;List all keys saved in memory. Use when user asks to see all information saved&quot;)<br>    public String dumpMemory() {<br>        var keys = redis.keys(&quot;*&quot;);<br>        if (keys.isEmpty()) {<br>            return &quot;There is no information to dump!&quot;;<br>        }<br><br>        return &quot;Keys found: &quot; + String.join(&quot;,&quot;, keys);<br>    }<br>}</pre><p>Looking at the Memory Tool file, we can see that the code is not very complex — actually, it’s pretty simple 😄</p><p>It basically contains methods that read from Redis or write data into Redis, along with some basic error handling. The most interesting part here is the annotation above each method.</p><p>As explained earlier in this article, the @Tool annotation from LangChain4j signals to the framework that these methods are tools that can be used by the AI model 🤖🔧</p><p>Inside the @Tool annotation, we must write a very clear instruction because the AI uses this text description to match the user’s intention with the correct method execution. So, for example, if I ask the AI model something like:</p><ul><li>“Save some information for me, please…”</li></ul><p>The AI model can understand that it should call the saveInMemory() method and execute that specific action 🧠</p><p>Now let’s take a look at the other tool, located in the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-agents-basics/src/main/java/com/augusto/aiagentsbasics/tools/NoteTool.java">NoteTool.java</a></p><pre>@Component<br>public class NoteTool {<br><br>    @Value(&quot;${notes.path}&quot;)<br>    private String notesPath;<br><br>    @Tool(&quot;Save a note into a file. Use when user asks to write or save a text.&quot;)<br>    public String saveNote(String fileName, String content) {<br>        Path path = Path.of(notesPath, fileName);<br>        try {<br>            Files.createDirectories(path.getParent());<br>            Files.writeString(path, content, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);<br>            return &quot;Note has been saved with name: &quot; + fileName;<br>        } catch (IOException e) {<br>            return &quot;Error while saving note: &quot; + e.getMessage();<br>        }<br>    }<br><br>    @Tool(&quot;Read the content from a saved note. Use when user asks to read or see a note.&quot;)<br>    public String loadNote(String fileName) {<br>        Path path = Path.of(notesPath, fileName);<br>        if (!Files.exists(path)) {<br>            return &quot;Note with name: &quot; + fileName + &quot;.txt does not exist&quot;;<br>        }<br>        try {<br>            return Files.readString(path);<br>        } catch (IOException e) {<br>            return &quot;Error while reading note: &quot; + e.getMessage();<br>        }<br>    }<br><br>    @Tool(&quot;List all saved notes. Use when user asks to see which notes exists.&quot;)<br>    public String listNotes() {<br>        Path path = Path.of(notesPath);<br>        try {<br>            Files.createDirectories(path);<br>            String notes = Files.list(path)<br>                    .map(filePath -&gt; filePath.getFileName().toString())<br>                    .collect(Collectors.joining(&quot;, &quot;));<br>            return notes.isEmpty() ? &quot;No notes saved yet!&quot; : &quot;Saved notes: &quot; + notes;<br>        } catch (IOException e) {<br>            return &quot;Error while listing notes: &quot; + e.getMessage();<br>        }<br><br>    }<br>}</pre><p>This tool is very similar to the previous one, with the difference that it writes a file into the destination folder containing the content I asked the AI to take notes about 📝</p><p>Just like the other tool, the code inside the methods is not complex — it’s basically simple Java file read/write operations. Here we also use the same @Tool annotation from LangChain4j, including a description explaining what the tool does.</p><p>Take a look at the description and notice that I explicitly used the word “note” to help the AI understand that it should save a note into the folder we previously configured in the application.properties file 🤖⚡</p><p>Now that we’ve analyzed the application step by step, let’s start it and see how it behaves in practice 🚀 To test the application:</p><ol><li>Start Docker using the command shown previously.</li><li>Run the Java application from your IDE.</li></ol><p>Once the application is running, it will be available on port 8080 at localhost. Let’s start by saving something into our Redis database — basically storing information in memory through the AI 🧠</p><p>Call the following GET endpoint using this cURL request:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=save in memory that i need to study&quot;</pre><p>The response from the AI model should look something like this 🤖💬:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*v-EPblS5lubOPD4CXRGezA.png" /><figcaption>AI saving to memory</figcaption></figure><p>Now, let’s take a look at Redis running on localhost to verify whether the information was actually saved 🧠🚀You should be able to see the stored memory inside Redis, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ezr3KtEcc59tWgAn9-oUHQ.png" /><figcaption>Inside redis database</figcaption></figure><p>Here in Redis, before calling the endpoint, I executed the FLUSHALL command to reset the database to a clean state 🧹</p><p>After that, I called the endpoint shown above and searched for the key that the AI model said it used to store the information.</p><p>Everything looks good so far 🚀 Now let’s test the memory retrieval functionality 🧠</p><p>To do that, we’ll call the same endpoint again, but this time changing the message parameter to the following request:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=do you remember what i need to do later?&quot;</pre><p>The response should look something similar to this 🧠🤖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*AOBx0yZaT9xNrB2-wbq3_A.png" /><figcaption>Response from AI when remembering something</figcaption></figure><p>Here, the AI searched our Redis database to check whether we had previously saved something into memory — and we actually did 🧠🚀</p><p>So the AI found the stored information and answered that “I need to study later”. The last method available in the Memory Tool is the one responsible for listing all keys currently saved in memory.</p><p>Let’s see how the AI model responds when we ask it to list all keys stored in the Redis database 🤖 Use the following cURL request:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=list all keys saved in memory&quot;</pre><p>The response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*WnclLJ3Y3DiwFhL5xGqJzw.png" /><figcaption>List all keys from memory</figcaption></figure><p>Ok, everything is working well with the Memory Tool we developed 🧠🚀</p><p>Now let’s test the Note Tool 📝 The first thing we need to do is call the endpoint asking the AI to save a note for us. Use the following cURL request:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=save a note for me using what i asked you to remember&quot;</pre><p>Here I’m asking the AI to combine both tools together 😄 It will need to:</p><ol><li>search the information stored in memory,</li><li>retrieve the saved content,</li><li>and then create a note file using that information.</li></ol><p>Let’s see the response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*PlqrUb06P3TVD2buA7e9uw.png" /><figcaption>note created</figcaption></figure><p>The response from the AI looked good 😄</p><p>Now let’s check inside the project folder resources/notes to verify whether the note was actually saved there 📝🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8158pYSzBvBp8bVE_5QIQ.png" /><figcaption>saved note</figcaption></figure><p>It looks like the combination of tools worked really well 😄🤖</p><p>Now let’s test the note-reading functionality we implemented. Call the following endpoint:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=what do i have in my note list todo1?&quot;</pre><p>This time, the AI should use the Note Tool to read the content from the todo1 note file and return the information saved inside it 📝🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*jwrK_fU7R6F28rWNsEsHQw.png" /><figcaption>response of content of note saved</figcaption></figure><p>The last method we have available is the one responsible for listing all saved notes 📝 Let’s test it by calling the following endpoint:</p><pre>curl &quot;http://localhost:8080/agent/chat?message=list all my notes&quot;</pre><p>The AI should use the Note Tool to scan the notes directory and return all note files currently saved there 🚀🤖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*gGrMwCrWLPlB68_8BuQyvQ.png" /><figcaption>List all notes</figcaption></figure><p>All tools are working well! 🚀🤖</p><p>Another interesting thing to mention is that if we ask the AI model to add something to the list, it can intelligently update the existing note and append the new information.</p><p>What’s cool here is that we never explicitly created an “edit note” tool 😄</p><p>So the AI adapts and reuses the “create note” tool in a different way to achieve the objective — almost like improvising with the tools it already has available. This shows how flexible AI agents can become when combined with a good set of tools 🔧🧠</p><p>With this approach, we can create many different tools for AI agents and automate a huge variety of tasks in our daily workflow. And honestly… that’s pretty awesome to think about 💻⚡🤖</p><p>And with that, we now have a fully operational AI Agents system running in the Java ecosystem 🚀☕🤖</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h4>Bibliography:</h4><p><a href="https://medium.com/@jamestang/building-agentic-ai-applications-with-langchain4j-using-agents-as-tools-0b83995f818c">Building Agentic AI Applications with LangChain4j: Using Agents as Tools | by James Tang | Medium</a></p><p><a href="https://javapro.io/2025/04/23/build-ai-apps-and-agents-in-java-hands-on-with-langchain4j/">Build AI Apps and Agents in Java: Hands-On with LangChain4j — JAVAPRO International</a></p><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/ai-agents-basics">Java-Series/ai-agents-basics at master · AugustoKlaic/Java-Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67aef4657948" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: AI]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-ai-ebaa7ee2d0d2?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebaa7ee2d0d2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Wed, 13 May 2026 03:11:34 GMT</pubDate>
            <atom:updated>2026-05-13T03:11:34.499Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>RAG systems</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*-ruX30a6IiUzi6CNryuvJQ.png" /></figure><p>So, let’s talk about RAG systems in the Java environment! 🚀</p><p>Nowadays, AI is the hottest topic. Everybody is talking about it, using it, automating things… but most of the time people are just surface-level users of AI. Here, we’ll explore a subtopic of AI systems called RAG systems, connected to the Java ecosystem.</p><p>RAG stands for “Retrieval-Augmented Generation”. It means the AI system will search a database for information and add relevant context to the answer given to the user’s question. The response can be fully personalized using user-specific context from basically any kind of source. So, if you saved notes from a class or a course you’ve taken, the AI can use them to answer questions about that content 📚🤖</p><p>RAG systems are a mix of technologies working together to generate personalized answers. They use embedding models, vector databases, LLMs, and math — yeah, math 😅</p><ul><li><strong>Embedding model:</strong> responsible for converting text into numeric vector arrays using mathematical operations.</li><li><strong>Vector databases:</strong> responsible for storing vectors alongside the original text chunks.</li><li><strong>LLM:</strong> receives the user’s question plus the relevant text chunks to generate a response.</li><li><strong>Chunks:</strong> smaller pieces of text extracted from a document. The smallest unit is called a token — it can represent a whole word or even part of a word.</li></ul><p>The flow usually works like this:</p><h4>Saving process 📥</h4><p>Documents (.pdf, .md, .txt, ...)<br> → Document chunking<br> → Conversion into vectors (embedding model)<br> → Storage inside a vector database</p><h4>Answer generation process ⚡</h4><p>User asks something<br> → Question converted into vectors (embedding model)<br> → Database searches for similar vectors<br> → Relevant chunks retrieved<br> → LLM receives chunks + question<br> → Final answer generated</p><p>The saving process converts and stores the data inside a specific type of database called a vector database. It basically works by splitting the entire file into smaller chunks of text. These chunks are then converted into numeric arrays — called vectors — and stored in the database together with the original plain text.</p><p>So now, the entire document is stored as numerical vectors like this:</p><pre>Original phrase: <strong>Hi my name is Augusto!</strong><br><br>Text converted into vector (384 dimensions, showing first 10):<br><strong>[-0.112, 0.019, 0.047, 0.082, -0.060, 0.027, -0.046, 0.095, -0.088, 0.032, ...]</strong></pre><p>Now that all the files have been converted and stored in the database, it’s time for the AI to trigger a search and personalize the response 🔎🤖</p><p>The answer generation process usually starts with a user interaction — for example, someone asking a question. The AI receives the question and sends it to the embedding model, which converts the text into a numeric array, just like it did with the documents previously stored in the database.</p><p>Something like this:</p><pre>Question: <strong>What is my name?<br><br></strong>Text converted into vector (384 dimensions, showing first 10):<br><strong>[-0.098, 0.024, 0.039, 0.071, -0.051, 0.019, -0.038, 0.087, -0.079, 0.028, ...]</strong></pre><p>Then, the database is queried to find vectors similar to the question vector. If the question contains words or concepts that were previously used in the documents, the vector conversion process will generate numerically similar arrays. This tells the database that the stored content is related to the user’s question, so the relevant information is returned to the AI to generate a contextualized response 🧠⚡</p><p>Using the previous document and question vectors as examples, the vector database performs cosine similarity calculations to measure how related the contents are. If the similarity score is close to 1, it indicates that the texts are highly related.</p><p>After finding the relevant information, the retrieved chunks are sent to the LLM, which then generates the personalized answer.</p><p>This technology is extremely useful for speeding up information retrieval from large documents or massive collections of files 📚🚀 People and companies can benefit from it by creating automated search systems, intelligent information retrieval, personalized responses, summaries, internal assistants, and much more.</p><p>That’s exactly why this type of AI system is so hyped nowadays 😄</p><p>Now that we’ve learned the concept, let’s build a simple RAG system. So… let’s code! 💻🔥</p><p>For this implementation we will use <strong>Spring Boot</strong> as the Java framework, <strong>LangChain4j</strong> to orchestrate the RAG pipeline, <strong>PGVector</strong> as our vector database running on Docker, and <strong>OpenRouter</strong> to access free LLM models via API 🤖☕</p><p>All files used in this project can be found on the project’s <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/ai-rag-basics">Github page</a>.</p><p>Let’s start with the build.gradle file:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.4.5&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.airagbasics&#39;<br>version = &#39;0.0.1&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br><br>    implementation platform(&#39;dev.langchain4j:langchain4j-bom:1.0.0&#39;)<br><br>    // LangChain4j core<br>    implementation &#39;dev.langchain4j:langchain4j&#39;<br><br>    // embedding model<br>    implementation &#39;dev.langchain4j:langchain4j-embeddings-e5-small-v2&#39;<br><br>    // OpenRouter (compatível com OpenAI)<br>    implementation &#39;dev.langchain4j:langchain4j-open-ai&#39;<br><br>    // PGVector<br>    implementation &#39;dev.langchain4j:langchain4j-pgvector&#39;<br>}</pre><p>Inside the build.gradle file, we have all the dependencies needed to build our simple RAG system 🚀</p><h4>Vector database dependency: PGVector</h4><p>→ Responsible for the communication between the application and the vector database — querying, storing embeddings, similarity searches, and all that good stuff.</p><h4>OpenRouter dependency: OpenRouter</h4><p>→ Basically, because I don’t have a NASA-level PC capable of running a local LLM 😅 So we’ll use an online and free model instead. OpenRouter provides some really good options for that.</p><h4>Embedding model dependency: Embeddings-e5-small</h4><p>→ This dependency is responsible for converting text into numeric vector arrays, which are later stored and searched inside the vector database.</p><h4>LangChain4j core dependency: LangChain4j</h4><p>→ Used to handle the core AI functionalities. It abstracts model integrations, API calls, embedding configuration, document chunking, and much more.</p><h4>Spring Boot framework: Spring Boot Starter</h4><p>→ Provides the server setup and the core functionalities of the Spring ecosystem ☕</p><p>Moving to the next step of the project, we have the docker-compose file.</p><p>Docker here is used simply to configure and run our vector database environment 🐳Take a look at the file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/pgvector-docker-compose.yml">pgvector-docker-compose.yml</a></p><pre>services:<br>  postgres:<br>    image: pgvector/pgvector:pg17<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      POSTGRES_DB: ragdb<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>    volumes:<br>      - pgvector_data:/var/lib/postgresql/data<br><br>volumes:<br>  pgvector_data:</pre><p>It’s pretty straightforward 😄</p><p>This configuration creates a PGVector database running on port 5432, with:</p><ul><li><strong>Database name:</strong> ragdb</li><li><strong>User:</strong> postgres</li><li><strong>Password:</strong> postgres</li></ul><p>It also creates a Docker volume to persist the data, so your vectors won’t disappear every time the container restarts 🐳 To run the database, open the folder where the file is located in your terminal and execute the following command:</p><pre>docker-compose -p pgvector -f pgvector-docker-compose.yml up -d</pre><p>Once Docker finishes building the container, you’ll have a fully functional PGVector server ready to store and query vector data 🚀</p><p>To finish the project configuration, we still need to add some properties to the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/src/main/resources/application.properties">application.properties</a> file inside the resources folder. This file tells Spring:</p><ul><li>how to connect to the database,</li><li>which API token should be used to authenticate with OpenRouter,</li><li>and where our local files are stored 📂</li></ul><p>Take a look at the configuration:</p><pre># OpenRouter - LLM in cloud<br>spring.ai.openai.api-key={YOUR_KEY}<br>spring.ai.openai.base-url=https://openrouter.ai/api/v1<br><br># PGVector - local vector database<br>pgvector.host=localhost<br>pgvector.port=5432<br>pgvector.database=ragdb<br>pgvector.user=postgres<br>pgvector.password=postgres<br><br># folder where files will be stored<br>documents.path=ai-rag-basics/src/main/resources/documents</pre><p>When running the project, remember to add your personal OpenRouter API token 🔑🤖</p><p>The database connection will happen automatically. The documents.path property defines where all the files used by the AI will be stored — basically, the knowledge base the RAG system will use to generate responses for us 📚Now, moving to the main part of the project, we have:</p><ul><li>2 service classes,</li><li>1 configuration class,</li><li>and 1 controller.</li></ul><p>The application works in a pretty simple way:</p><ul><li>One service is responsible for ingesting documents into the vector database.</li><li>The other service receives questions or prompts from the user and generates personalized answers using the stored context ⚡</li></ul><p>Let’s take a look into the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/src/main/java/com/augusto/airagbasics/config/RagConfig.java">RagConfig.java</a> files first:</p><pre>@Configuration<br>public class RagConfig {<br><br>    @Value(&quot;${spring.ai.openai.api-key}&quot;)<br>    private String apiKey;<br><br>    @Value(&quot;${spring.ai.openai.base-url}&quot;)<br>    private String baseUrl;<br><br>    @Value(&quot;${pgvector.host}&quot;)<br>    private String pgHost;<br><br>    @Value(&quot;${pgvector.port}&quot;)<br>    private Integer pgPort;<br><br>    @Value(&quot;${pgvector.database}&quot;)<br>    private String pgDatabase;<br><br>    @Value(&quot;${pgvector.user}&quot;)<br>    private String pgUser;<br><br>    @Value(&quot;${pgvector.password}&quot;)<br>    private String pgPassword;<br><br>    /*<br>        for understanding language and generating responses<br>     */<br>    @Bean<br>    public OpenAiChatModel chatModel() {<br>        return OpenAiChatModel.builder()<br>                .apiKey(apiKey)<br>                .baseUrl(baseUrl)<br>                .modelName(&quot;openai/gpt-oss-120b:free&quot;)<br>                .build();<br>    }<br><br>    /*<br>        to convert text into numeric vectors<br>     */<br>    @Bean<br>    public EmbeddingModel embeddingModel() {<br>        return new E5SmallV2EmbeddingModel();<br>    }<br><br>    /*<br>        to store and retrieve the vectors<br>     */<br>    @Bean<br>    public EmbeddingStore&lt;TextSegment&gt; embeddingStore() {<br>        return PgVectorEmbeddingStore.builder()<br>                .host(pgHost)<br>                .port(pgPort)<br>                .database(pgDatabase)<br>                .user(pgUser)<br>                .password(pgPassword)<br>                .table(&quot;documents&quot;)<br>                .dimension(384)<br>                .createTable(true)<br>                .build();<br>    }<br>}</pre><p>In this configuration file — as explained by the comments above each bean — we create the specific beans that Spring will use to make the whole RAG pipeline work ☕⚙️</p><ul><li>The chatModel bean connects to OpenRouter and configures the free LLM model that will be used by the application.</li><li>The embeddingModel bean is responsible for creating the component that converts text chunks into numeric vector arrays.</li><li>The embeddingStore bean establishes communication with the vector database. Inside this bean, we define details such as the database table, vector dimensions, and other storage configurations 📦🧠</li></ul><p>Going to the next part, let’s take a look into the controller class: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/src/main/java/com/augusto/airagbasics/controller/ChatController.java">ChatController.java</a></p><pre>@RestController<br>@RequestMapping(&quot;/ai-rag&quot;)<br>public class ChatController {<br><br>    private final ChatService chatService;<br>    private final DocumentIngestionService documentIngestionService;<br><br>    public ChatController(ChatService chatService, DocumentIngestionService documentIngestionService) {<br>        this.chatService = chatService;<br>        this.documentIngestionService = documentIngestionService;<br>    }<br><br>    @PostMapping(&quot;/ingest&quot;)<br>    public String ingestDocument() {<br>        documentIngestionService.ingestDocument();<br>        return &quot;Ingestion Done&quot;;<br>    }<br><br>    @DeleteMapping(&quot;/ingest&quot;)<br>    public String deleteIngestion() {<br>        documentIngestionService.deleteIngestion();<br>        return &quot;Ingestion Cleared&quot;;<br>    }<br><br>    @GetMapping(&quot;/chat&quot;)<br>    public String chat(@RequestParam String question) {<br>        return chatService.chat(question);<br>    }<br>}</pre><p>This is just a simple controller exposing REST endpoints to perform basic operations such as:</p><ul><li>ingesting a document,</li><li>deleting ingested data,</li><li>and asking questions to the AI model 🤖</li></ul><p>Nothing too fancy here 😄</p><p>Now we move to the service layer, where the actual logic behind saving vectors and calling the chat model lives.</p><p>In this project, we have two services:</p><ul><li>one responsible for document ingestion into the vector database,</li><li>and another responsible for interacting with the AI model and generating responses based on the stored context ⚡</li></ul><p>Check the file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/src/main/java/com/augusto/airagbasics/chat/ChatService.java">ChatService.java</a>:</p><pre>@Service<br>public class ChatService {<br><br>    interface Assistant {<br>        String chat(String message);<br>    }<br><br>    private final Assistant assistant;<br><br>    public ChatService(OpenAiChatModel chatModel,<br>                       EmbeddingModel embeddingModel,<br>                       EmbeddingStore&lt;TextSegment&gt; embeddingStore) {<br><br>        EmbeddingStoreContentRetriever retriever = EmbeddingStoreContentRetriever.builder()<br>                .embeddingStore(embeddingStore)<br>                .embeddingModel(embeddingModel)<br>                .maxResults(3)<br>                .build();<br><br>        this.assistant = AiServices.builder(Assistant.class)<br>                .chatModel(chatModel)<br>                .contentRetriever(retriever)<br>                .build();<br>    }<br><br>    public String chat(String question) {<br>        return assistant.chat(question);<br>    }<br>}</pre><p>In the chat service, we use a constructor to inject our beans into the Assistant interface, which is an abstraction implemented at runtime by LangChain4j 🤖</p><p>You basically define the contract of the interface, and AiServices.builder() dynamically creates the implementation for you — pretty similar to how Spring Data JPA generates repository implementations automatically, but now for AI services 😄</p><p>In our case, the service simply receives a String containing the user’s question and returns another String containing the AI-generated answer.</p><p>Now going to the last part of our <em>RAG</em> system we have the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/ai-rag-basics/src/main/java/com/augusto/airagbasics/ingestion/DocumentIngestionService.java">DocumentIngestionService.java</a>:</p><pre>@Service<br>public class DocumentIngestionService {<br><br>    private static final Integer CHUNK_SIZE = 500;<br>    private static final Integer CHUNK_OVERLAP = 50;<br><br>    private final EmbeddingModel embeddingModel;<br>    private final EmbeddingStore&lt;TextSegment&gt; embeddingStore;<br><br>    private final String documentPath;<br><br><br>    public DocumentIngestionService(EmbeddingModel embeddingModel,<br>                                    EmbeddingStore&lt;TextSegment&gt; embeddingStore,<br>                                    @Value(&quot;${documents.path}&quot;) String documentPath) {<br>        this.embeddingModel = embeddingModel;<br>        this.embeddingStore = embeddingStore;<br>        this.documentPath = documentPath;<br>    }<br><br>    public void deleteIngestion() {<br>        embeddingStore.removeAll();<br>        System.out.println(&quot;Ingestion cleared&quot;);<br>    }<br><br>    public void ingestDocument() {<br>        List&lt;Document&gt; documents = FileSystemDocumentLoader.loadDocuments(Path.of(documentPath));<br><br>        EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()<br>                .documentSplitter(DocumentSplitters.recursive(CHUNK_SIZE, CHUNK_OVERLAP))<br>                .embeddingModel(embeddingModel)<br>                .embeddingStore(embeddingStore)<br>                .build();<br><br>        ingestor.ingest(documents);<br>        System.out.println(&quot;Indexed &quot; + documents.size() + &quot; documents&quot;);<br>    }<br>}</pre><p>Here we handle the logic responsible for ingesting documents and deleting existing ingestions 📚⚙️ We inject both the embeddingModel and the embeddingStore into the service so we can:</p><ul><li>convert text into numeric vectors</li><li>and store those vectors inside the vector database.</li></ul><p>This is also where we define the chunk size used to split the documents before generating embeddings ✂️🧠</p><p>Now that everything is configured, let’s test our RAG system by calling the endpoints and verifying the results 🚀 For that, we’ll need an OpenRouter API token to access a free LLM model.</p><p>So, head over to the <a href="https://openrouter.ai/">OpenRouter website</a>, create an account, and then navigate to the <strong>API Keys</strong> menu. After that, generate a new key using the button in the top-right corner 🔑</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpFUtAk6ZpuIMPpktbjctw.png" /></figure><p>Give your API key a name, copy it to your clipboard, and save it somewhere safe 🔐 After the key is created, you won’t be able to see it again.</p><p>Next, paste the key into the environment variable configured inside the application.properties file of the project. Now we need to choose an LLM model and configure it inside the RagConfig.java file 🤖</p><p>On the OpenRouter website, use the model search bar located in the top-left corner and search for the word free. This will display all LLM models currently available for free.</p><p>Choose a model focused on <strong>text generation</strong>, since our application is generating answers and conversational responses. That type of model will fit our use case much better 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KriLF5ZcKe3oTJtVNsVeoA.png" /></figure><p>Click on a model and, on the next screen that appears, copy the model name and paste it into the .modelName() method inside the chatModel bean ⚙️🤖 After that, hit <strong>Run</strong> in your IDE 🚀 Once the application is up and running, take a look at the folder:</p><pre>ai-rag-basics/src/main/resources/documents</pre><p>Inside it, you’ll find a text document explaining what a RAG system is. This document will be ingested into our vector database using the following endpoint:</p><pre>POST http://localhost:8080/ai-rag/ingest</pre><p>If everything works correctly, you should receive a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30whJ0yBskG2pErH0kz4fQ.png" /><figcaption>ingestion done</figcaption></figure><p>Now our AI model has contextual information from the document and can search through it to generate more cohesive and personalized responses 🤖📚</p><p>In this case, it will use the ingested content to help us better understand what a RAG system is. To get an answer from the AI, call the following endpoint:</p><pre>GET http://localhost:8080/ai-rag/chat?question=what is a rag system?</pre><p>You should receive a response similar to the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8TmYvE_b-MLBm9AM_mjl5w.png" /><figcaption>Generated response from LLM</figcaption></figure><p>Remember that AI is generative, so the answers may be different from the one I received — and that’s completely expected 😄</p><p>The important part is that the response maintains the same context, meaning, and correctness based on the ingested documents.</p><p>And with that, we now have a fully operational RAG system running in the Java ecosystem 🚀☕🤖</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h4>Bibliography:</h4><p><a href="https://www.iso.org/artificial-intelligence">ISO — Artificial intelligence: What it is, how it works and why it matters</a></p><p><a href="https://openrouter.ai/">OpenRouter</a></p><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/ai-rag-basics">Java-Series/ai-rag-basics at master · AugustoKlaic/Java-Series</a></p><p><a href="https://huggingface.co/blog/ngxson/make-your-own-rag">Code a simple RAG from scratch</a></p><p><a href="https://huggingface.co/blog/getting-started-with-embeddings">Getting Started With Embeddings</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebaa7ee2d0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Series: Secrets Management]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-secrets-management-c2827b383a8a?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2827b383a8a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[secret-management-tools]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 20:08:05 GMT</pubDate>
            <atom:updated>2026-04-01T20:08:05.020Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Vault &amp; Jenkins</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rJjpMl6260ABrl81.png" /></figure><p><strong>Let’s talk about Secret management in Java!</strong></p><p>Today, we care a lot about security in this digital world we live in. We store a lot of sensitive data online and definitely don’t want anyone having unauthorized access to it, right? 🔐<br> So, modern applications must guarantee that their resources are accessed only by authorized entities.</p><p>Even a simple application can have multiple connection tokens, passwords, and service-user credentials for external services, databases, or other resources. This information is required to authenticate and access those resources. The danger here is obvious: if a hacker gets access to these credentials, they can potentially access all the data stored in those services and cause serious damage. 💥</p><p>Because of that, applications must not use literal or hard-coded strings in application.properties files—let alone directly in the code. Otherwise, sensitive connection data might end up in logs, SCM tools like GitHub, or build pipelines, where it could be exposed and exploited.</p><p>That being said, in real-world scenarios, applications rely on a secret management tool to handle all credentials — logins, passwords, tokens, and related data. This tool provides a secure environment to store sensitive information, acting as a centralized and controlled access point for all connection credentials. Much better for both security and maintainability. 🛡️</p><p>With a secret management tool in place, the application no longer contains hard-coded credentials or even stores them in properties files. Instead, it uses placeholders like ${placeholder}, which are replaced with the actual values at build time. These secrets are injected into the application by the build tool—such as Jenkins. In this setup, the build tool is the only component that directly communicates with the secret management system.</p><p>The build tool accesses the secret management system using a secret key generated by the framework. This key must be securely stored — usually as a variable in the build tool — or made accessible through a secure mechanism. It controls access to credentials by authorizing build tools and users through these keys. However, it’s important to note: this setup doesn’t eliminate human error. If someone accidentally leaks the key… well, that’s a problem. 😬</p><p>In this article, I created a Java project that uses sensitive credentials that must not be exposed. To handle this, I used Vault by HashiCorp to securely store all secrets, and Jenkins as the build tool. You can find everything in my <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/secret-management-basics">GitHub repo</a>. So, let’s code! 🚀</p><p>To start this tutorial, we’ll need a very simple Java application — almost with no dependencies — just the Spring Web Starter. This is enough to create an endpoint that will run inside a container and return a response confirming that the secrets were successfully injected. So the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/build.gradle"><strong><em>build.gradle </em></strong></a>is very simple:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.5.3&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br><br>group = &#39;com.augusto.secretmanagement&#39;<br>version = &#39;0.0.1&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>}<br><br>test {<br>    useJUnitPlatform()<br>}</pre><p>After running the Gradle script and importing all dependencies, let’s create a simple <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/src/main/resources/application.properties">application.properties</a> file that will contain our placeholders to receive the secrets from the secret management framework. It should look something like this: ✨</p><pre>spring.application.name=secret-management-basics<br><br>database.password: ${DB_PASSWORD:NOT_INJECTED}<br>api.key: ${API_KEY:NOT_INJECTED}<br>app.env: ${APP_ENV:NOT_INJECTED}</pre><p>In the application.properties file, you can see that I added a default value to each property. This value will be used in case the secret injection does not happen. For now, it’s just for testing purposes—to validate that the properties are being resolved correctly. 🧪</p><p>After creating the application.properties, let’s build a simple Controller to expose a GET endpoint that returns a JSON with the secrets—for testing purposes only! ⚠️</p><p>The <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/src/main/java/com/augusto/secretmanagement/controller/SecretManagementeController.java">controller </a>should be like this:</p><pre>@RestController<br>@RequestMapping(&quot;/secrets&quot;)<br>public class SecretManagementeController {<br><br>    @Value(&quot;${database.password}&quot;)<br>    private String dbPassword;<br><br>    @Value(&quot;${api.key}&quot;)<br>    private String apiKey;<br><br>    @Value(&quot;${app.env}&quot;)<br>    private String appEnv;<br><br>    @GetMapping<br>    public Map&lt;String, String&gt; showSecrets() {<br>        return Map.of(<br>                &quot;db_password&quot;, dbPassword,<br>                &quot;api_key&quot;, apiKey,<br>                &quot;app_env&quot;, appEnv<br>        );<br>    }<br>}</pre><p>Let’s test and see what it returns with the current configuration — without injecting any secrets yet. Start the Spring Boot application in your IDE and call the GET endpoint at http://localhost:8080/secrets to check the response: 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jls3n_AqYOWXwRl79KArhw.png" /><figcaption>Return without injecting secrets</figcaption></figure><p>As we can see, the application returns the fallback default values for the secrets, since we didn’t provide any environment variables to resolve the placeholders. Because of that, the value NOT_INJECTED is used.</p><p>Now, let’s take a look at the Docker Compose file of the project to understand the other components involved in this setup. 🐳</p><p>For our Docker environment, we’ll need four services:</p><ul><li>Jenkins master server, to store all configurations</li><li>Jenkins agent (slave), to build and deploy our Java application</li><li>DinD (Docker-in-Docker), to run our Java application</li><li>Vault, to securely store the secrets 🔐</li></ul><p>Let’s check the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/secret-management-docker.yml">secret-management-docker.yml</a> file. Here, I’ll break down the Docker Compose configuration by service and explain each one individually—but in the GitHub repository, you’ll find the complete file. 🚀</p><pre>version: &quot;3&quot;<br><br>services:<br><br>  vault:<br>    image: hashicorp/vault:latest<br>    container_name: vault<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8200:8200&quot;<br>    environment:<br>      - VAULT_DEV_ROOT_TOKEN_ID=root-token<br>      - VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200<br>      - VAULT_ADDR=http://0.0.0.0:8200<br>    cap_add:<br>      - IPC_LOCK<br>    networks:<br>      - jenkins<br><br>networks:<br>  jenkins:</pre><p>Starting with our secret management tool — the first service defined in the Docker Compose file. In this tutorial, as mentioned before, I’m using Vault from HashiCorp in development mode, which is free and intended for testing purposes. 🧪</p><p>Vault works as a centralized safe for secrets — passwords, tokens, API keys, certificates, and more. Everything is securely encrypted at rest and only accessible through explicit path-based authentication. All access is logged and audited, which adds an extra layer of security. 🔐</p><p>In Vault, everything is stored under a specific path. Because of that, access must always be explicitly defined for each path. To manage this, Vault uses roles and policies, allowing us to control exactly who can access what, and what actions they can perform on the stored secrets.</p><p>To configure all of this, we first need to run the Vault container. In the terminal, navigate to the folder where the file is located and run the following command: docker compose -f secret-management-docker.yml up -d Then, wait for all services to start. 🚀</p><p>Everything in Vault can be configured via command line. To do that, we need to access the running Vault container. In a terminal, run:docker exec -it vault sh</p><p>Once inside the container, use the following commands to configure roles, policies, secrets, and the authentication method:</p><pre>export VAULT_ADDR=http://vault:8200<br>export VAULT_TOKEN=root-token<br><br># 1. Enable AppRole<br>vault auth enable -path=jenkins-role approle<br><br># 2. Create Jenkins&#39;s policy<br>vault policy write jenkins-policy - &lt;&lt;EOF<br>path &quot;secret/data/java-secrets-demo&quot; {<br>  capabilities = [&quot;read&quot;]<br>}<br>EOF<br><br># 3. Create policy&#39;s role<br>vault write auth/jenkins-role/role/jenkins-role \<br>  token_policies=&quot;jenkins-policy&quot; \<br>  token_ttl=1h \<br>  token_max_ttl=4h<br><br># 4. Create app&#39;s secrets<br>vault kv put secret/java-secrets-demo \<br>  DB_PASSWORD=&quot;my-secret-password&quot; \<br>  API_KEY=&quot;abc123-key-xpto&quot; \<br>  APP_ENV=&quot;development&quot;</pre><p>Vault is now fully configured and ready to do its job. 🚀 You can also log in and explore all the configurations through the Vault UI — just access the default URL: <a href="http://localhost:8200.">http://localhost:8200</a></p><p>Keep in mind that this is running in development mode, so data is not persisted. If the container is restarted, you’ll need to configure everything again. ⚠️</p><p>The next part of our project involves Jenkins and its agent. So, let’s take a look at the Docker Compose configuration responsible for starting both of them:</p><pre> jenkins:<br>    image: jenkins/jenkins:lts-jdk21<br>    container_name: jenkins<br>    restart: unless-stopped<br>    user: root<br>    ports:<br>      - &quot;8090:8080&quot;<br>      - &quot;50000:50000&quot;<br>    environment:<br>      - DOCKER_HOST=tcp://docker:2376<br>      - DOCKER_CERT_PATH=/certs/client<br>      - DOCKER_TLS_VERIFY=1<br>    volumes:<br>      - jenkins_home:/var/jenkins_home<br>      - jenkins_certs:/certs/client:ro<br>    networks:<br>      - jenkins<br>    depends_on:<br>      - jenkins-dind<br>      - vault<br><br>  jenkins-dind:<br>    image: docker:dind<br>    container_name: jenkins-dind<br>    restart: unless-stopped<br>    privileged: true<br>    environment:<br>      - DOCKER_TLS_CERTDIR=/certs<br>    volumes:<br>      - jenkins_certs:/certs/client<br>    expose:<br>      - 2376<br>    ports:<br>      - &quot;8080:8080&quot;<br>    networks:<br>      jenkins:<br>        aliases:<br>          - docker<br><br>  jenkins-agent-01:<br>    image: jenkins/inbound-agent:latest-jdk21<br>    container_name: jenkins-agent-01<br>    restart: unless-stopped<br>    user: root<br>    entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;apt-get update &amp;&amp; apt-get install -y docker.io git &amp;&amp; git config --global --add safe.directory &#39;*&#39; &amp;&amp; /usr/local/bin/jenkins-agent&quot;]<br>    environment:<br>      - JENKINS_URL=http://jenkins:8080<br>      - JENKINS_AGENT_NAME=agent-01<br>      - JENKINS_SECRET={AGENT_CONNECTION_STRING}<br>      - JENKINS_TUNNEL=jenkins:50000<br>      - DOCKER_HOST=tcp://docker:2376<br>      - DOCKER_CERT_PATH=/certs/client<br>      - DOCKER_TLS_VERIFY=1<br>    volumes:<br>      - jenkins_certs:/certs/client:ro<br>    networks:<br>      - jenkins<br>    depends_on:<br>      - jenkins<br>      - jenkins-dind<br><br>volumes:<br>  jenkins_home:<br>    driver: local<br>  jenkins_certs:<br>    driver: local<br><br>networks:<br>  jenkins:</pre><p>All of these services defined in the Docker Compose file above complete our environment. Here’s what we have:</p><ul><li>A Jenkins server running on port 8090—responsible for storing all configurations to access secrets in Vault, and for fetching the Jenkinsfile from my GitHub repository, which defines the steps of our build.</li><li>A Jenkins agent — the agent connects to the Jenkins server using an auto-generated token and executes the steps defined in the Jenkinsfile.</li><li>A DinD (Docker-in-Docker) container — responsible for hosting our application in an isolated environment, built from a Dockerfile. 🐳</li></ul><p>The key point here is that the agent must be able to execute both Git and Docker commands. For that reason, the agent service includes a custom entrypoint script to handle these requirements.</p><p>I also have another article on Medium where I explain how to properly configure Jenkins with an agent, so feel free to check it out for more details: <a href="https://medium.com/@augusto.klaic/java-series-ci-cd-79671f05e0f9">Java series: CI/CD. Jenkins | by Augusto Sopelsa Klaic | Medium</a></p><p>It’s pretty much the same setup — the main difference is that in this project I’m not using the Gradle plugin in Jenkins. Because of that, you’ll need to commit the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/gradlew">gradlew</a> wrapper and its dependencies to the repository.</p><p>Once all containers are up and running, access the Jenkins server and connect the agent. You’ll need to generate a token, add it to the Docker Compose configuration, and rebuild the Jenkins agent service. After that, configure the pipeline by setting Jenkins to retrieve the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/secret-management-basics/Jenkinsfile">Jenkinsfile</a> from the SCM. 🚀</p><p>To finalize the setup and ensure the pipeline runs correctly, we need to install the Vault plugin in Jenkins and configure it to retrieve credentials from the secret management tool.</p><p>To install the Vault plugin, go to the Jenkins menu, open “Plugins,” search for “Vault,” and install it.</p><p>After that, we need to configure the secrets. To retrieve them, access the Vault container again by running: docker exec -it vault sh Then, execute the following command:</p><pre># 5. Get Role ID<br>vault read -field=role_id auth/jenkins-role/role/jenkins-role/role-id<br><br># 6. Generate Secret ID<br>vault write -f -field=secret_id auth/jenkins-role/role/jenkins-role/secret-id</pre><p>This will generate two UUID strings — these are the secret keys that Jenkins needs to authenticate with Vault and retrieve the required data. 🔑</p><p>After getting these two values, go to the Jenkins configuration menu and click on “Credentials” under the security section. Then, click on “Add Credentials” in the top-right corner, select “Vault App Role Credential,” and fill in the fields as follows:</p><ul><li><strong>Scope:</strong> Global</li><li><strong>ID:</strong> vault-approle</li><li><strong>Role ID:</strong> the value generated by the role ID command above</li><li><strong>Secret ID:</strong> the value generated by the secret ID command above</li><li><strong>Path:</strong> jenkins-role</li></ul><p>The <strong>ID</strong> can be anything you want — just make sure to use the same value in your Jenkinsfile otherwise, Jenkins won’t be able to retrieve the secrets from Vault.</p><p>The <strong>Path</strong> must match the one previously configured in Vault. You can change it if needed, but both sides must be consistent.</p><p>Now we have everything configured and ready to run our test. Start all Docker containers using the command shared earlier, then go to the Jenkins job we created — our pipeline — and click “Build Now.” 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*D-GgBsyJebfKPxl_-4PJOA.png" /><figcaption>This indicates a successfull build</figcaption></figure><p>If the build fails, check the logs to understand what went wrong. But if everything runs successfully, you can access http://localhost:8080/secrets and see the response with the secrets properly injected into the application at build time. 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9RmojPNUxap3o3LI57FaA.png" /><figcaption>secrets injected successfully</figcaption></figure><p>Now you have a secret management tool up and running to protect all the sensitive credentials of a Java application. 🔐</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography:</h3><p><a href="https://www.hashicorp.com/en/products/vault">HashiCorp Vault | Identity-based secrets management</a></p><p><a href="https://www.jenkins.io/">Jenkins</a></p><p><a href="https://plugins.jenkins.io/hashicorp-vault-plugin/">HashiCorp Vault | Jenkins plugin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2827b383a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Unit testing]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-unit-testing-71394f9a424c?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/71394f9a424c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 18:42:54 GMT</pubDate>
            <atom:updated>2026-03-20T18:42:54.213Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>JUnit &amp; Mockito</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*JuoIPtZZnAwy_5dr" /></figure><p><strong>Let’s talk about unit tests in Java! ☕💻</strong></p><p>Software engineering nowadays depends on several steps. These steps are essential to guarantee quality and proper functionality of the final product. One very important step is testing the application — and we have many testing approaches, like unit tests, integration tests, functional tests, behavior tests, and more… 🧪</p><p>In this text, I’m going to talk specifically about the unit testing approach and its benefits. Unit tests usually happen right after the coding phase — or even before, like in the TDD approach — and they are written by the developer who implemented the business rules. This helps guarantee that the code is doing exactly what it is supposed to do 🎯</p><p>The unit testing process happens in cycles. It’s a repeated loop of coding, testing, checking, and correcting (or refactoring). This iteration between code and testing can happen in different ways:</p><ul><li>TDD (Test Driven Development) — the most famous one 🏆</li><li>BDD (Behavior Driven Development)</li><li>Code-first testing — test after development</li><li>Automated testing</li></ul><p>These cycles usually follow phases like: code → test → check → correct → refactor 🔄 The methodologies mentioned above (like TDD) just change the order of these steps depending on their philosophy. For example, TDD starts by writing tests first, then the code, then checking, correcting, and refactoring.</p><p>All of them have their pros and cons, but in the end, they all help improve the quality of the final product 🚀</p><p>Unit tests are widely used in software engineering. Almost every serious project or company ensures they are in place. They are very important for project maturity and bring a lot of benefits — especially when code coverage is above ~80% 📊</p><p>Some of these benefits are:</p><ul><li>Live documentation for developers — especially new hires 📚</li><li>Code safety — changes bring fewer surprises</li><li>Code trust — the code does what it is meant to do 🤝</li><li>Easy refactoring — tests guarantee that the logic still works properly</li><li>Bug reduction — errors are caught before complex integrations 🐛</li></ul><p>So basically, unit testing has become a core step in software engineering because it brings so many benefits — way more than the time a developer spends writing tests ⏱️</p><p>In large projects, there are tools to enforce minimum coverage — like SonarQube — and code reviews may be rejected if there are no tests for the code being submitted for merge. All of this exists to make sure tests are not skipped 🚫 The name “unit test” means we should test each unit of our code. In other words, test functions, methods, and classes that contain important logic.</p><p>To do that, we write independent pieces of code that execute the logic from the main code. For example, if we have a function that adds two numbers, the test will call that function and compare the actual result with the expected result ➕ This process is repeated for each small piece of logic — or at least most of it.</p><p>The Java testing ecosystem follows some common patterns. All test files should be inside the test folder, usually under src/test/java. Another common pattern is naming: the test class should have the same name as the class being tested, plus the suffix Test.</p><p>Inside each test file, we have methods annotated with @Test, containing the test logic. That’s the basic foundation 🧱</p><p>In unit testing — especially in large projects — we make heavy use of mocks. They are a core part of unit testing because they help isolate responsibilities.</p><p>Everything external to the code being tested should not affect the test. Unit tests are meant to be fast and lightweight ⚡<br> So it’s not a good idea to start a database, call real external services, or depend on other systems just to run tests. That’s where mocks come in.</p><p>Mocking means telling the test how to behave when external interactions happen. For example, if a method calls a database or an external API, we can mock that call to return a predefined object — or do nothing in case of void.</p><p>Mocks allow us to test code in isolation by simulating the behavior of external dependencies 🎭</p><p>Another core part of unit testing is verification. For that, we use assertions (asserts). These are methods that compare the expected result with the actual result.</p><p>If the assertion fails, the test fails — simple as that ❌ The result of these assertions is captured by the test framework and shown in the test reports.</p><p>Speaking of frameworks, in Java unit testing we usually rely on tools like JUnit and Mockito. They make a powerful combo — providing assertions and mocking capabilities — allowing us to properly isolate and validate our code 🔥</p><p>In this article, I created a Java project focused on building a strong unit testing setup that can be reused in most projects. I also explored many features of these frameworks to create well-structured and maintainable tests. All of that can be found at my <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/unit-testing">GitHub repo</a>. So let’s code!!</p><p><strong>Presenting this Java testing tutorial project 🧪💻</strong></p><p>To set things up, we need to add some dependencies to our build script. These dependencies will be imported via the Gradle build script and are related to randomness, package organization, boilerplate reduction, and basic Spring testing support ⚙️</p><p>So yeah… a little bit of everything to make our life easier 😄</p><p>Now, let’s take a look at the build.gradle file and see what’s going on there 👇</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.5.3&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.unittesting&#39;<br>version = &#39;0.0.1&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral() <br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    compileOnly &#39;org.projectlombok:lombok&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok&#39;<br><br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testImplementation &#39;org.instancio:instancio-junit:5.4.1&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>    testCompileOnly &#39;org.projectlombok:lombok&#39;<br>    testAnnotationProcessor &#39;org.projectlombok:lombok&#39;<br>    testImplementation &#39;com.tngtech.archunit:archunit-junit5-api:1.4.1&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><ul><li><strong>spring-boot-starter-test</strong> — The default Spring Boot testing toolkit. It comes packed with JUnit, Mockito, AssertJ, and several utilities to build both unit and integration tests. Basically, your testing starter pack 🚀</li><li><strong>instancio-junit</strong> — A library that automatically generates objects with randomized data. Super useful for creating diverse test scenarios without manually instantiating everything (because nobody wants to write 50 setters, right? 😅)</li><li><strong>junit-platform-launcher</strong> — Responsible for starting and running JUnit tests. It’s required to execute your test suite via Gradle or directly from your IDE 🧩</li><li><strong>archunit-junit5-api</strong> — Allows you to write tests that validate your project architecture (package structure, naming conventions, allowed dependencies, etc.). Great to keep the codebase clean and organized over time 🏗️</li><li><strong>lombok (compileOnly / testCompileOnly + annotationProcessor)</strong> — Provides annotations to reduce boilerplate (getters, setters, builders…). In tests, it makes it much easier to create data objects and helper classes ✨</li></ul><p>Inside the src folder, we have the main logic of the project — these are the classes that will actually be tested. It’s not necessary to show all of them here, but you can check them out at: <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/unit-testing/src/main/java/com/augusto/unittesting">my github</a>.</p><h4><strong>Structure and setup — the basics every unit test should have 🧱</strong></h4><p>Unit testing a small piece of code can be easy… but take that to a large project and boom — chaos starts to show up 😅</p><p>You’ll see multiple functions doing the same thing across different test files, repeated annotations everywhere, and sometimes almost no useful information during test execution. Not a very fun scenario…</p><p>To help solve this, a good approach is to create a <strong>TestBase</strong> class. This class centralizes common behaviors between tests and provides helper methods that can be reused across the entire test suite 🔁</p><p>Of course, every project will have its own helpers and shared logic. The one I created here is just an example to demonstrate some possibilities — not a golden rule 👍</p><p>So, let’s take a look at it: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/config/UnitTestBase.java"><strong><em>UnitTestBase.java</em></strong></a> file:</p><pre>@Slf4j<br>@ExtendWith(MockitoExtension.class)<br>public abstract class UnitTestBase {<br><br>    private Clock clock;<br>    private Instant start;<br>    protected InOrder inOrder;<br><br>    @BeforeEach<br>    void setup(TestInfo testInfo) {<br>        this.clock = Clock.systemDefaultZone();<br>        this.start = Instant.now(clock);<br>        log.info(&quot;Starting test: {}&quot;, testInfo.getDisplayName());<br>    }<br><br>    @AfterEach<br>    void tearDown(TestInfo testInfo) {<br>        Instant end = Instant.now(clock);<br>        Duration duration = Duration.between(start, end);<br>        log.info(&quot;Finished test: {} in {} ms&quot;, testInfo.getDisplayName(), duration.toMillis());<br>    }<br><br>    @SafeVarargs<br>    protected final &lt;T&gt; void inOrderOf(T... mocks) {<br>        this.inOrder = inOrder((Object[]) mocks);<br>    }<br>}</pre><p>In this file, I tried to create some utility logging functions that show the start and the end of each test method. I also added an initializer for <strong>inOrder</strong> verification, which will be explained later 👀</p><p>Another cool thing here is that we can declare all the required annotations only once in this class. Then, every other test class that extends it will automatically inherit this configuration — saving us some lines of code and a lot of typing ✨</p><p>Of course, this base class could include many other features, like default JSON parsing configuration or additional helper methods. But for this project, this setup is already enough to demonstrate the benefits of using a base class in unit testing 👍</p><h4><strong>Hardcoded test data is not the best way ❌</strong></h4><p>To build a good unit test suite, it’s important to pay attention to the data and objects you’re using. If you create a test scenario where all the data is manually set — already knowing what values will make the test pass — you’re basically creating a <em>rigged test</em> 🎯 (and yeah… that’s dangerous 😅)</p><p>A classic example is working with dates and time ⏰ Let’s say you create a function that calculates a payment date and checks if it’s overdue or not. If you hardcode the date, the test might pass today… but in a week, it can start failing for no good reason.</p><p>To avoid these kinds of flaky tests, a better approach is to use randomized data 🎲 There are many libraries that help with this, and in this project, I chose to use <strong>Instancio</strong>.</p><p>A good practice here is to create a <strong>Factory</strong> class responsible for generating these objects with random data. You can even create one factory per domain to keep things more organized 🏗️</p><p>Below follows the <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/fixture/TestFactory.java">TestFactory.java</a> with the fixture of objects for the unit testing process of the project:</p><pre>public class TestFactory {<br><br>    public static Person createPersonOver18Years() {<br>        return Instancio.of(Person.class)<br>                .generate(field(Person::getId), gen -&gt; gen.longs().range(1L, 100L))<br>                .generate(field(Person::getName), gen -&gt; gen.text().pattern(&quot;Person####&quot;))<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(18, 30))<br>                .create();<br>    }<br><br>    public static Person createInvalidAgePerson() {<br>        return Instancio.of(Person.class)<br>                .generate(field(Person::getId), gen -&gt; gen.longs().range(1L, 100L))<br>                .generate(field(Person::getName), gen -&gt; gen.text().pattern(&quot;Person####&quot;))<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(0, 17))<br>                .create();<br>    }<br><br>    public static Person createInvalidNamePerson() {<br>        return Instancio.of(Person.class)<br>                .generate(field(Person::getId), gen -&gt; gen.longs().range(1L, 100L))<br>                .supply(field(Person::getName), () -&gt; &quot;admin&quot;)<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(18, 30))<br>                .create();<br>    }<br><br>    public static Person createPersonWithoutId() {<br>        return Instancio.of(Person.class)<br>                .ignore(field(Person::getId))<br>                .generate(field(Person::getName), gen -&gt; gen.text().pattern(&quot;Person####&quot;))<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(18, 80))<br>                .create();<br>    }<br><br>    public static Person createPersonWithoutIdAndName(String name) {<br>        return Instancio.of(Person.class)<br>                .ignore(field(Person::getId))<br>                .set(field(Person::getName), name)<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(18, 80))<br>                .create();<br>    }<br><br>    public static Person createPersonWithoutIdAndAge(Integer age) {<br>        return Instancio.of(Person.class)<br>                .ignore(field(Person::getId))<br>                .generate(field(Person::getName), gen -&gt; gen.text().pattern(&quot;Person####&quot;))<br>                .set(field(Person::getAge), age)<br>                .create();<br>    }<br><br>    public static List&lt;Person&gt; createListPerson() {<br>        return Instancio.ofList(Person.class)<br>                .size(5)<br>                .generate(field(Person::getAge), gen -&gt; gen.ints().range(18, 80))<br>                .generate(field(Person::getName), gen -&gt; gen.text().pattern(&quot;Person####&quot;))<br>                .generate(field(Person::getId), gen -&gt; gen.longs().range(1L, 100L))<br>                .create();<br>    }<br><br>    public static Stream&lt;String&gt; generateValidNames() {<br>        return Instancio.ofList(String.class)<br>                .size(5)<br>                .generate(Select.all(String.class), gen -&gt; gen.string().length(5))<br>                .filter(Select.all(String.class), val -&gt; !val.toString().equalsIgnoreCase(&quot;admin&quot;))<br>                .create()<br>                .stream();<br>    }<br><br>    public static Stream&lt;String&gt; generateInvalidName() {<br>        return Stream.of(&quot;admin&quot;);<br>    }<br><br>    public static Stream&lt;Integer&gt; generateRandomAges() {<br>        return Instancio.ofList(Integer.class)<br>                .size(10)<br>                .generate(Select.allInts(), gen -&gt; gen.ints().range(18, 80))<br>                .create()<br>                .stream();<br>    }<br>}</pre><p>Each method in the <strong>TestFactory</strong> fits into one or more test cases. They were created to represent business rule scenarios and help unit tests achieve the minimum code coverage 📊</p><p>With <strong>Instancio</strong>, you can generate random data and also configure some parameters for the generation — like string prefixes, number ranges, list sizes, and many other features 🎲</p><p>Another great point is the ability to generate streams of random data. This works really well when combined with @ParameterizedTest from JUnit, because it allows you to run the same test scenario multiple times with different inputs.</p><p>Each execution is different from the previous one, which helps ensure that your test is actually validating the business rules — and not just passing by coincidence 😅</p><h4><strong>Mock vs Spy 🤼</strong></h4><p>We can’t skip talking about these two guys. They are core tools in unit testing because they help transform tightly coupled classes into more testable, decoupled ones 🔌</p><p>Both <strong>mock</strong> and <strong>spy</strong> are provided by the Mockito library (usually used together with JUnit). They allow us to change the behavior of methods — either by modifying return values or overriding what a method does.</p><p>Imagine you have a service class that calls two other services. You can’t properly unit test it as-is, because those dependencies are involved. That’s where mock and spy come in, depending on what you need:</p><ul><li>If you want to fully mock a class and its methods (meaning the real methods won’t be called at all), you should use <strong>mock</strong> 🎭</li><li>If you want to call the real method but override some behavior or returned values during execution, you should use <strong>spy</strong> 👀</li></ul><p>Both tools aim to achieve a similar goal: decoupling classes for unit testing purposes, making it easier to validate the business rules inside a service class 💡</p><p>In our project, there are several examples of both approaches — but let’s start with a mock example from the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceWithMockTest.java"><em>PersonServiceWithMockTest.java</em></a></p><pre>class PersonServiceWithMockTest extends UnitTestBase {<br>    @Mock<br>    private PersonRepository repository;<br><br>    @Mock<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Test<br>    void shouldCreatePersonSuccessfully() {<br>        Person dto = TestFactory.createPersonWithoutId();<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br><br>        Person result = service.create(dto);<br><br>        assertNotNull(result);<br>        assertEquals(dto.getId(), result.getId());<br>        assertEquals(dto.getName(), result.getName());<br>        assertEquals(dto.getAge(), result.getAge());<br>        verify(notificationService, times(1)).sendWelcomeMessage(dto.getName());<br>        verify(repository, times(1)).save(dto);<br>    }<br>}<br><br>class PersonServiceWithSpyTest extends UnitTestBase {<br>    @Mock<br>    private PersonRepository repository;<br><br>    @Spy<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Test<br>    void shouldCallRealNotificationAndLogForCreate() {<br>        Person dto = createPersonWithoutId();<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br><br>        Person result = service.create(dto);<br><br>        assertEquals(dto.getName(), result.getName());<br>        verify(notificationService).sendWelcomeMessage(result.getName());<br>    }<br>}</pre><p>In the example above, from files <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceWithMockTest.java">PersonServiceWithMockTest </a>and <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceWithSpyTest.java">PersonServiceWithSpyTest</a>, we can see that the <strong>NotificationService</strong> is mocked differently in each case. So, let’s check the logs to understand the difference between <strong>mock</strong> and <strong>spy</strong> — where one completely bypasses the execution of sendWelcomeMessage, while the other actually executes what is defined inside the method body 👀</p><p>Mocked test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xBukTU381LL_xHaj7rqzA.png" /><figcaption>test with mock</figcaption></figure><p>Spied test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOwOFxXIKm6uin6Of3b-Bg.png" /><figcaption>test with spy</figcaption></figure><p>Now we can clearly see the difference between the two types of tests — and choose wisely how to use each one 🎯</p><h4><strong>doReturn() vs thenReturn() ⚔️</strong></h4><p>Still on this topic, we have another interesting detail in unit testing: how values are returned when working with mocked or spied methods.</p><p>In fully mocked tests, this doesn’t make much difference, because the real method is never called anyway. But in <strong>spied tests</strong>, this difference can be subtle — and sometimes very important 👀</p><p>When we use doReturn(), the real method is <strong>not invoked</strong>. The return value is simply replaced, making it a safer option in scenarios where calling the real method could cause problems ⚠️</p><p>On the other hand, when using thenReturn(), the real method <strong>is invoked</strong> before returning the mocked value. This can lead to unexpected side effects, depending on what the method actually does 😅</p><p>Let’s take a look at an example from the project. Go to the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceUsingThenReturnAndDoReturnTest.java">PersonServiceUsingThenReturnAndDoReturnTest.java</a></p><pre>public class PersonServiceUsingThenReturnAndDoReturnTest extends UnitTestBase {<br>    @Mock<br>    private PersonRepository repository;<br><br>    @Spy<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Test<br>    void shouldMockMethodSafelyWithDoReturn() {<br>        doReturn(&quot;MockedPrefix&quot;).when(notificationService).getWelcomePrefix();<br>        Person input = TestFactory.createPersonWithoutId();<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br>        service.create(input);<br>        verify(notificationService, times(1)).getWelcomePrefix();<br>    }<br><br>    @Test<br>    void shouldExecuteRealMethodWithThenReturn() {<br>        when(notificationService.getWelcomePrefix()).thenReturn(&quot;MockedPrefix&quot;);<br><br>        Person input = TestFactory.createPersonWithoutId();<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br>        service.create(input);<br><br>        verify(notificationService, times(1)).getWelcomePrefix();<br>    }<br>}</pre><p>Here we have a <strong>spy test</strong> using different return approaches. We can check the difference in the execution logs to better understand what’s happening under the hood 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aytpVByHvBqnuuR7We6QPQ.png" /><figcaption>logs from the tests</figcaption></figure><p>Looking at the logs, we can see that the unit test using thenReturn() actually executed the call to getWelcomePrefix, while the test using doReturn() did <strong>not</strong> call that method. Both tests executed the real method sendWelcomeMessage from the notification service, but only one triggered getWelcomePrefix.</p><p>So, when we just want to control the returned value and don’t really care about executing the method itself, it’s better to use doReturn() — this helps avoid unwanted side effects caused by method execution when using thenReturn() ⚠️</p><h4><strong>doAnswer() vs thenAnswer() — dynamic responses 🎯</strong></h4><p>Still talking about returning values from mocked methods, we have another interesting category here.</p><p>The difference between them follows the same idea as we saw before:</p><ul><li>When using <strong>then*</strong> methods, the real method is called during stubbing</li><li>When using <strong>do*</strong> methods, the method is <strong>not</strong> called</li></ul><p>The key difference is that doAnswer() and thenAnswer() allow us to create <strong>dynamic responses</strong>, meaning the return value can be calculated based on the input parameters of the method 🔥</p><p>Let’s take a look at an example from the project: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceUsingThenAnswerAndDoAnswerTest.java"><em>PersonServiceUsingThenAnswerAndDoAnswerTest.java</em></a></p><pre>public class PersonServiceUsingThenAnswerAndDoAnswerTest extends UnitTestBase {<br><br>    @Mock<br>    private PersonRepository repository;<br><br>    @Mock<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Test<br>    void shouldCreatePersonSuccessfully() {<br>        Person dto = TestFactory.createPersonWithoutId();<br><br>        doAnswer(invocation -&gt; {<br>            String name = invocation.getArgument(0);<br>            assertEquals(name, dto.getName());<br>            return null;<br>        }).when(notificationService).sendWelcomeMessage(anyString());<br><br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br><br>        Person result = service.create(dto);<br>        verify(notificationService).sendWelcomeMessage(result.getName());<br>    }<br>}</pre><p>In this example file, the first mock using doAnswer() behaves similarly to doReturn(). It does not log anything from <strong>NotificationService</strong> — only the start and end of the test execution — because the real method is not called 🚫</p><p>Comparing with the second mock using thenAnswer(), the repository will actually call save() during the stubbing process. However, it will only return the value defined in the lambda expression 🎯</p><h4><strong>doCallRealMethod() — mock context 🔧</strong></h4><p>One more thing in this mocking and spying context: we can explicitly trigger the execution of the real method from a mocked or spied class using doCallRealMethod() or thenCallRealMethod() 👀</p><p>It’s pretty straightforward — you use it when you need the real behavior of a method. For example, when mocking a class under test but still needing a specific method to run (maybe to modify some internal state), using callRealMethod() is a great option. It avoids creating a “fake” stub that always returns the same value and doesn’t reflect real behavior ⚠️</p><p>You can check some examples of this in the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/PersonServiceTest.java"><em>PersonServiceTest.java</em></a><em>.</em></p><h4><strong>Then/Do &amp; Return/Answer — best usage 🎯</strong></h4><p>These four operators have a “right way” to be used. We can think about them in two axes:</p><ul><li><strong>Chained syntax</strong> — (then*) → has some subtle issues in certain scenarios. <br>For example, with <strong>void methods</strong> or <strong>methods from spied classes</strong>. <br>As mentioned before, when using then*, the real method is <strong>called during stubbing</strong>. And that brings some problems:<br>- How do you chain a return value for a <strong>void method</strong>? 🤔<br>- What if the method in a <strong>spy</strong> triggers unexpected behavior or even calls a database? 💣</li><li><strong>Inverted syntax</strong> — (do*) → can do basically the same as then* in terms of returning values, but with one key difference: <br>It <strong>does not call the real method during stubbing</strong>. <br>This makes it a safer and more flexible option, especially in the scenarios mentioned above — avoiding unwanted side effects and giving you more control over the test execution ⚡</li></ul><pre>| // Fail: cannot chain .thenReturn() in void<br>| when(emailService.send(any())).thenReturn(???);<br>|<br>| // Correct: inverted syntax is the only syntax that works with void<br>| doNothing().when(emailService).send(any());<br>----------------------------------------------------------------------<br>| // Dangerous: call get(0) in empty list → IndexOutOfBoundsException<br>| @Spy<br>| List&lt;String&gt; list = new ArrayList&lt;&gt;();<br>| when(list.get(0)).thenReturn(&quot;value&quot;);<br>|<br>| // Safe: do not call eral method during setup<br>| doReturn(&quot;value&quot;).when(list).get(0);</pre><p>Most of the time, then* will be used because it is more readable and organized 🧼</p><p>The do* approach is usually applied in those specific scenarios where then* cannot properly handle the situation (like void methods or spies with side effects) ⚠️</p><ul><li><strong>Fixed value — (</strong><strong>Return) → </strong>Always returns the same value — a fixed value — independent of the arguments received 🔁</li><li><strong>Dynamic logic — (</strong><strong>Answer) → </strong>Receives an InvocationOnMock, allowing you to inspect the arguments, execute custom logic, or even throw exceptions. This makes it much more flexible for complex scenarios 🔥</li></ul><pre>| // Return the argument itself (standart in repository mocks)<br>| when(repository.save(any())).thenAnswer(inv -&gt; inv.getArgument(0));<br>|<br>| // Always return same value, no matter what is used as argument in save<br>| when(repository.save(any())).thenReturn(&quot;value&quot;);<br>---------------------------------------------------------------<br>| // Response based in the value of the argument<br>| when(cache.get(anyString())).thenAnswer(inv -&gt; {<br>|    String chave = inv.getArgument(0);<br>|    return chave.startsWith(&quot;user:&quot;) ? new User() : null;<br>| });</pre><p>Here, the most common usage will be the syntax with return, because it’s simpler and more direct 👍</p><p>The answer approach is usually reserved for more complex logic — when you need dynamic behavior or want to change the returned value based on the input 🔥</p><h4><strong>ArgumentCaptor — inspecting real values 🔍</strong></h4><p>The most basic idea of a unit test is to assert returned values — checking if the actual result matches what we expect. But sometimes, things are not that simple… 😅</p><p>It can be tricky to validate the value of a variable that is used inside an internal method call, especially when that value is not returned anywhere. Even if the dependency is mocked, that internal value might still be very important for the flow — and we may want to verify what was actually passed to it 👀 To solve this, we use <strong>ArgumentCaptor</strong>.</p><p>Let’s take a look at an example in the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceWithCaptorTest.java">PersonServiceWithCaptorTest.java</a></p><pre>public class PersonServiceWithCaptorTest extends UnitTestBase {<br><br>    @Mock<br>    private PersonRepository repository;<br><br>    @Mock<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Captor<br>    private ArgumentCaptor&lt;String&gt; messageCaptor;<br><br>    @BeforeEach<br>    public void setup() {<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br>        doNothing().when(notificationService).sendWelcomeMessage(anyString());<br><br>    }<br><br>    @Test<br>    void shouldCaptureMessageSentOnNotification() {<br>        Person dto = TestFactory.createPersonWithoutId();<br><br>        Person result = service.create(dto);<br>        verify(notificationService, times(1)).sendWelcomeMessage(messageCaptor.capture());<br>        assertEquals(result.getName(), messageCaptor.getValue());<br>    }<br><br>    @Test<br>    void shouldCaptureMessageSentOnNotificationUsingLocalCaptor() {<br>        Person dto = TestFactory.createPersonWithoutId();<br><br>        Person result = service.create(dto);<br>        ArgumentCaptor&lt;String&gt; messageCaptor = ArgumentCaptor.forClass(String.class);<br>        verify(notificationService, times(1)).sendWelcomeMessage(messageCaptor.capture());<br>        assertEquals(result.getName(), messageCaptor.getValue());<br>    }<br><br>    @Test<br>    void shouldCaptureMultipleValuesWhenSendingMessage() {<br>        List&lt;Person&gt; persons = TestFactory.createListPerson();<br><br>        List&lt;Person&gt; results = service.createAll(persons);<br>        ArgumentCaptor&lt;String&gt; nameCaptor = ArgumentCaptor.forClass(String.class);<br>        verify(notificationService, times(persons.size())).sendWelcomeMessage(nameCaptor.capture());<br><br>        assertEquals(results.size(), nameCaptor.getAllValues().size());<br><br>        for (int i = 0; i &lt; results.size(); i++) {<br>            assertEquals(results.get(i).getName(), nameCaptor.getAllValues().get(i));<br>        }<br>    }<br>}</pre><p>In this file, we can see some usage examples of <strong>ArgumentCaptor</strong>. It is always used together with the verify() method from Mockito 🧩</p><p>It’s also very common to see verify() being used with any() — another Mockito feature that basically says: “this parameter can be anything”.</p><p>But honestly… using any() in most situations is <strong>not a good practice</strong> ⚠️</p><p>Why? Because it can lead to false positives — tests passing when they shouldn’t. It may ignore important cases (like when a variable should not be null), and in the end, it makes the test harder to understand (what value was actually passed?) 🤔</p><p>All of this can lead to problems and make test maintenance harder over time. When facing these scenarios, the correct approach is to use <strong>ArgumentCaptor</strong>. It replaces the any() usage and captures the actual value passed to the mocked method, so we can assert and validate it later 🔍Once captured, we have access to the exact variable used in the call — no guessing involved.</p><p>In the example file mentioned above, we can see two ways of using <strong>ArgumentCaptor</strong>:</p><ul><li><strong>Method context</strong> → using argumentCaptor.forClass() (instantiated inside the test method)</li><li><strong>Class context</strong> → using the @Captor annotation</li></ul><p><strong>Method context</strong> 👍</p><ul><li>Better readability (no need to check types at the top of the class)</li><li>Ideal when the captor is used in a specific test only</li></ul><p><strong>Class context</strong> 🔁</p><ul><li>Better reusability across multiple test scenarios</li><li>Avoids repeating the same boilerplate code in different methods</li></ul><h4><strong>InOrder — guaranteeing the order of calls 🔄</strong></h4><p>This is a feature that I don’t often see being used in real-world applications… but it’s actually pretty useful 👀</p><p>It adds an extra layer of validation to your unit tests. InOrder is used together with Mockito’s verify() method to ensure that mocked methods are executed in the correct order.</p><p>If a verification is out of order — meaning the sequence of calls in the test does not match what actually happens in the system — the test will fail ❌</p><p>This is very helpful when the order of operations matters for the business logic. Let’s check an example in the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceInOrderTest.java"><em>PersonServiceInOrderTest.java</em></a></p><pre>public class PersonServiceInOrderTest extends UnitTestBase {<br><br>    @Mock<br>    private PersonRepository repository;<br><br>    @Mock<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    private InOrder inOrder;<br><br>    @BeforeEach<br>    void setup() {<br>        inOrder = inOrder(repository, notificationService);<br>    }<br><br>    @Test<br>    void shouldCreatePersonSuccessfully() {<br>        Person dto = TestFactory.createPersonWithoutId();<br><br>        doNothing().when(notificationService).sendWelcomeMessage(anyString());<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br><br>        Person result = service.create(dto);<br><br>        assertNotNull(result);<br>        assertEquals(dto.getId(), result.getId());<br>        assertEquals(dto.getName(), result.getName());<br>        assertEquals(dto.getAge(), result.getAge());<br><br>        inOrder.verify(repository, times(1)).save(dto);<br>        inOrder.verify(notificationService, times(1)).sendWelcomeMessage(dto.getName());<br>    }<br>}</pre><p>In the example, I instantiate the inOrder object using a helper method from <strong>UnitTestBase.java</strong>, which receives all the mocks used in the test class 🧩After that, it only needs to be used together with verify().</p><p>At the end of the test case, we can see two verify calls — and before each one, the inOrder reference is used.</p><p>If the order of these verifications is changed, the test will fail ❌ That’s because, in the real system, the repository call happens before the notificationService call — and InOrder is enforcing exactly that sequence 🔄</p><h4><strong>Other JUnit features 🧪</strong></h4><p>There are also other JUnit features that can make our tests easier to write and more organized.</p><p>Some of the ones I explored in this article are:</p><p><strong>@Nested annotation 🧱</strong></p><p>The @Nested annotation works as a way to organize unit tests. You can use it to group tests by business scenarios and even define shared variables specific to that context. This improves reusability and helps avoid issues with “dirty” test state 🧼</p><p>Let’s take a look at an example in the project, in the following file: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceUsingNestedTest.java">PersonServiceUsingNestedTest.java</a></p><pre>@Nested<br>    class CreatePerson {<br><br>        @Captor<br>        private ArgumentCaptor&lt;Person&gt; personCaptor;<br><br>        private void happyPathMocks() {<br>            lenient().when(repository.save(any(Person.class))).thenAnswer(ans -&gt; {<br>                Person person = ans.getArgument(0);<br>                person.setId(1L);<br>                return person;<br>            });<br><br>            lenient().doCallRealMethod().when(notificationService).sendWelcomeMessage(anyString());<br>        }<br><br>        private void verifyErrorMocksCalls() {<br>            verify(notificationService, never()).sendWelcomeMessage(anyString());<br>            verify(repository, never()).save(any(Person.class));<br>        }<br><br>        private void verifyInOrderMocksCalls() {<br>            inOrder.verify(repository, times(1)).save(personCaptor.capture());<br>            inOrder.verify(notificationService, times(1)).sendWelcomeMessage(personCaptor.getValue().getName());<br>        }<br><br>        @Test<br>        void shouldCreatePersonSuccessfully() {<br>            happyPathMocks();<br>            Person dto = TestFactory.createPersonWithoutId();<br>            Person result = personService.create(dto);<br><br>            assertNotNull(result);<br>            assertEquals(dto.getId(), result.getId());<br>            assertEquals(dto.getName(), result.getName());<br>            assertEquals(dto.getAge(), result.getAge());<br><br>            verifyInOrderMocksCalls();<br>        }<br><br>    }</pre><p>In the example file above, by using the @Nested annotation, I can better organize my test scenarios.</p><p>I can also create helper methods that are available only within that specific nested context — like the happyPathMocks() method, which is reused across multiple tests 🔁</p><p>I also created an <strong>ArgumentCaptor</strong> to be reused in all scenarios, since they all have in common the processing of a Person object. All of this helps keep the tests more organized, cleaner, and easier to read 👀✨</p><p><strong>@RepeatedTest &amp; @ParameterizedTest annotations 🔁</strong></p><p>These two annotations are great for different purposes:</p><ul><li>@RepeatedTest → allows a test to run multiple times. This is especially useful when combined with random data generation (like using Instancio) 🎲</li><li>@ParameterizedTest → allows a test to run with a data source, making it possible to validate multiple scenarios using different input datasets within the same test 📊</li></ul><p>Both approaches help increase test coverage and reduce duplicated code, keeping your tests cleaner and more efficient 🚀 Let’s take a look at an example from the project: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceRepeatedTest.java">PersonServiceRepeatedTest.java</a> and <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/PersonServiceTest.java">PersonServiceTest.java</a></p><pre>        @RepeatedTest(10)<br>        void shouldThrowExceptionWhenCreatePersonUnder18Years() {<br>            Person dto = TestFactory.createInvalidAgePerson();<br>            IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -&gt; personService.create(dto));<br>            assertEquals(&quot;Person must be over 18 years.&quot;, ex.getMessage());<br>            verifyErrorMocksCalls();<br>        }<br><br>        @ParameterizedTest(name = &quot;shouldAllowNamesOtherThanAdmin: &#39;&#39;{0}&#39;&#39;&quot;)<br>        @MethodSource(&quot;com.augusto.unittesting.fixture.TestFactory#generateValidNames&quot;)<br>        void shouldAllowNamesOtherThanAdmin(String name) {<br>            happyPathMocks();<br>            Person dto = TestFactory.createPersonWithoutIdAndName(name);<br>            Person result = personService.create(dto);<br>            assertEquals(name, result.getName());<br>            verifyInOrderMocksCalls();<br>        }<br><br>        @ParameterizedTest(name = &quot;shouldNotAllowAdminName&quot;)<br>        @MethodSource(&quot;com.augusto.unittesting.fixture.TestFactory#generateInvalidName&quot;)<br>        void shouldNotAllowAdminName(String name) {<br>            Person dto = TestFactory.createPersonWithoutIdAndName(name);<br>            assertThrows(RuntimeException.class, () -&gt; personService.create(dto));<br>            verifyErrorMocksCalls();<br>        }</pre><p>The @RepeatedTest will execute the test the number of times you specify in the annotation. For example, @RepeatedTest(10) will run the same test ten times 🔁 In this case, we are generating random data using the <strong>TestFactory</strong> class, making each execution a bit different 🎲</p><p>The @ParameterizedTest needs to be used together with the @MethodSource annotation. This annotation tells JUnit where the data will come from to fill the parameters defined in the test method signature. So basically, I’m telling JUnit to look at a specific method inside the <strong>TestFactory</strong> class, which will provide one or more sets of parameters for the test 📦</p><p>The @ParameterizedTest annotation ensures that the test will run multiple times — once for each data set provided by the source. This is a great way to avoid repeating the same test code for different data scenarios, keeping everything cleaner and more maintainable 🚀</p><p><strong>argThat() method 🎯</strong></p><p>Last but not least, we have the argThat() function. It allows us to validate fields of an argument without needing to use the <strong>ArgumentCaptor</strong> we discussed earlier 👀</p><p>The argThat() is used inside the verify() context. It captures the argument passed to the mocked method and lets us perform assertions directly on its fields. This can be a more concise and readable alternative in some scenarios, especially when you just need to validate specific properties of the object 🧩</p><p>Let’s take a look at an example from the project: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/service/testingjunitfeatures/PersonServiceUsingArgThatTest.java">PersonServiceUsingArgThatTest.java</a></p><pre>public class PersonServiceUsingArgThatTest extends UnitTestBase {<br><br>    @Mock<br>    private PersonRepository repository;<br><br>    @Mock<br>    private NotificationService notificationService;<br><br>    @InjectMocks<br>    private PersonService service;<br><br>    @Test<br>    void shouldCreatePersonAndVerifyWithArgThat() {<br>        Person dto = TestFactory.createPersonWithoutId();<br><br>        doNothing().when(notificationService).sendWelcomeMessage(anyString());<br>        when(repository.save(any(Person.class)))<br>                .thenAnswer(ans -&gt; {<br>                    Person person = ans.getArgument(0);<br>                    person.setId(1L);<br>                    return person;<br>                });<br><br>        Person result = service.create(dto);<br><br>        assertNotNull(result);<br>        assertEquals(dto.getId(), result.getId());<br>        assertEquals(dto.getName(), result.getName());<br>        assertEquals(dto.getAge(), result.getAge());<br><br>        verify(repository, times(1)).save(argThat(saved -&gt; saved.getName().equals(dto.getName())));<br>        verify(notificationService, times(1)).sendWelcomeMessage(argThat(sent -&gt; sent.equals(dto.getName())));<br>    }<br>}</pre><p>At the end of the test above, we can see the usage of argThat(). Pretty straightforward, right? 😄</p><h4><strong>ArchUnit — Testing project architecture 🏗️</strong></h4><p>Our last topic in this big unit testing article is <strong>ArchUnit</strong> — a library that treats your project structure and architectural rules as tests. And yeah… if a rule is violated, the build will fail ❌</p><p>With ArchUnit, we can define different sets of rules for our architecture tests. For example:</p><ul><li>Ensuring that one layer is not used inside another forbidden layer</li><li>Preventing a controller package from being imported inside a service package (which would break the layer separation) 🚫</li><li>Enforcing that every unit test <strong>must extend</strong> UnitTestBase, to keep consistency and reuse common behavior</li></ul><p>Basically, it works like a <strong>guardian of your project</strong> 🛡️</p><p>It ensures that every developer who contributes to the codebase follows the architectural rules and keeps the project clean and consistent over time. Let’s take a look at an example in the project: <a href="https://github.com/AugustoKlaic/Java-Series/blob/master/unit-testing/src/test/java/com/augusto/unittesting/architecture/ArchitectureTest.java">ArchitectureTest.java</a></p><pre>public class ArchitectureTest extends UnitTestBase {<br><br>    JavaClasses classes = new ClassFileImporter().importPackages(&quot;com.augusto.unittesting&quot;);<br><br>    @Test<br>    void shouldCheckDependencyBetweenControllerAndRepository() {<br>        ArchRuleDefinition.noClasses()<br>                .that().resideInAPackage(&quot;..repository..&quot;)<br>                .should().dependOnClassesThat().resideInAPackage(&quot;..controller..&quot;)<br>                .check(classes);<br>    }<br><br>    @Test<br>    void shouldCheckDependencyBetweenControllerAndService() {<br>        ArchRuleDefinition.noClasses()<br>                .that().resideInAPackage(&quot;..service..&quot;)<br>                .should().dependOnClassesThat().resideInAPackage(&quot;..controller..&quot;)<br>                .check(classes);<br>    }<br><br>    @Test<br>    void shouldCheckIfTestClassesExtendUnitTestBase() {<br>        ArchRuleDefinition.classes()<br>                .that().resideInAPackage(&quot;..unittesting..&quot;)<br>                .and().haveSimpleNameEndingWith(&quot;Test&quot;)<br>                .should().beAssignableTo(com.augusto.unittesting.config.UnitTestBase.class)<br>                .check(classes);<br>    }<br><br>}</pre><p>In the file, we can see three unit tests. Two of them are focused on package architecture organization — ensuring that no classes from the <strong>service layer</strong> are used inside the <strong>repository layer</strong>, and that no classes from the <strong>controller layer</strong> are used inside the <strong>service layer</strong> 🚫</p><p>The last test defines a standard for test classes: all of them must have the suffix Test at the end of the file name and must extend the base unit test class.</p><p>And that’s it! 🎉 Now we have a solid test setup that can be used across different projects — covering multiple needs while staying clean, reusable, and well-organized 🚀</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography:</h3><p><a href="https://www.baeldung.com/java-unit-testing-best-practices">Best Practices for Unit Testing in Java | Baeldung</a></p><p><a href="https://www.archunit.org/">Unit test your Java architecture — ArchUnit</a></p><p><a href="https://junit.org/">JUnit</a></p><p><a href="https://site.mockito.org/">Mockito framework site</a></p><p><a href="https://www.instancio.org/">Instancio: Test Data Generator for Java — Instancio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71394f9a424c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: APIs]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-apis-d649f853b477?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/d649f853b477</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[bff]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 20:12:04 GMT</pubDate>
            <atom:updated>2025-07-02T20:14:05.534Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>GraphQL</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*7G3RuyA51668TpDX" /></figure><p><strong>Today let’s talk about exposing resources in Java using GraphQL.</strong></p><p>I think the first way most developers learn to expose resources is through REST APIs, because it’s simple and easy to understand. It’s still the most popular approach in Java nowadays, so it’s easy to find documentation online or questions that help solve problems.</p><p>From my experience, it’s without a doubt the method I’ve used the most to expose information — making GET, POST, PUT, PATCH, and DELETE requests using the REST controller from Spring Boot 🛠️.</p><p>That being said, technology has evolved, and other ways of exposing data have emerged. One of them is GraphQL, which is the topic of this text right here 😄.</p><p>GraphQL is also a new topic for me, because I’ve never used it in any real project — neither in my career nor in my personal POCs. But it’s a cool subject to study, because it’s quite different from the REST way of doing things. So let’s go 🚀</p><p>GraphQL is an alternative to SOAP, REST, and gRPC. It’s a query language for APIs that retrieves data from a server. Its main goal is to solve some common REST problems, like <strong>underfetching</strong> (when not enough data is returned, so you need more calls) and <strong>overfetching</strong> (when too much data is returned — more than you actually need).</p><p>An interesting point to notice between REST controllers and GraphQL is that the contract logic is inverted 🔄. When calling REST endpoints, the contract is defined by the server. But in GraphQL, the power to define the contract is on the <strong>client side</strong>.</p><p>For example, in a Java REST client, if an endpoint returns an object, that object will come with <em>all</em> its properties in the JSON representation. You can’t just say “give me only the name&quot; — not without changing the server code.</p><p>But in GraphQL, that’s exactly what you can do 💡The client decides <strong>exactly</strong> which fields it wants.</p><p>This inversion of the traditional contract logic (compared to REST, where only the server defines the rules) is possible in GraphQL because it’s <strong>statically typed</strong>. That means the server defines a fixed, known structure. This is done through the <strong>schema file</strong>, which exposes the API contract to the client — allowing it to build and personalize the requests with only the data it needs 📦.</p><p>The <strong>schema file</strong> is the contract itself between the server and the client. It defines all the data structure available in the API, like:</p><ul><li>What data types exist</li><li>What fields those data types have</li><li>What operations are possible (queries and mutations) ⚙️</li></ul><p>This schema file is usually called schema.graphqls, and it has a specific format: it’s written using <strong>SDL – Schema Definition Language</strong> 📜.</p><p>SDL is used to define everything GraphQL can do — its operations, types, and queries. It’s a <strong>declarative language</strong>, organized in a way that’s kind of similar to a JSON data structure. The difference is that <strong>JSON</strong> is a runtime representation of data (what you send or receive), while <strong>SDL</strong> describes the <strong>contract</strong> of an API — the structure that both client and server agree on 🤝.</p><p>The <strong>schema file</strong> defines the operations that the client will be able to perform. These operations can be for <strong>reading</strong> or <strong>writing</strong> data, and are grouped into three core types:</p><ul><li><strong>Query</strong> –<br>Read operations. The client asks for the exact data it wants, and the server responds in the same structure 📦.</li><li><strong>Mutation</strong> –<br>Write operations. These are the equivalent of REST’s POST, PUT, or DELETE methods ✍️.</li><li><strong>Subscription</strong> –<br>Useful for real-time data streaming, like receiving updates as soon as something changes 🔄📡.</li></ul><p>These operations are the core building blocks. On top of them, we can add more advanced behavior using <strong>resolvers</strong>, which allow us to customize the logic for each operation.</p><p><strong>Resolver</strong> –<br>Resolvers are used in any GraphQL operation. They are functions that handle the logic behind each field being queried or mutated 🧠.</p><p>For example, imagine the client asks for a nested object, and this nested object is composed of data coming from different sources (like a database + an API). One resolver function can be responsible for fetching one part, while another resolver handles the rest. Together, they build the final response the client needs 🛠️.</p><p><strong>GraphQL is now widely used as a data orchestrator layer in real-world systems</strong>, aggregating information from multiple sources — like data centers, REST services, and files — and <strong>unifying access to data through a single entry point</strong>. In microservice architectures, it often acts as an <strong>API Gateway</strong>.</p><p>This architecture is also known as <strong>BFF — Backend for Frontend</strong> 💡. In this role, GraphQL becomes a centralized entry point that connects backend services to frontend applications — simplifying access to data across the board 🧩.</p><p>It’s important to understand that <strong>GraphQL is not an autonomous application</strong> — it’s a <strong>specification</strong>, or an <strong>API model</strong>. To work, it always needs a server that will:</p><ul><li>Interpret queries</li><li>Validate them against the schema</li><li>Execute resolvers to fetch the requested data</li></ul><p>Each GraphQL implementation (Node.js, Java, Python, Go…) has its own server to be deployed. For Java — which is our focus here — we have tools like <a href="https://www.graphql-java.com/">graphql-java</a> and <a href="https://spring.io/projects/spring-graphql">spring-graphql</a> that integrate GraphQL into a Spring Boot application, running on a server like Tomcat or Jetty ☕🚀.</p><p>Another cool benefit of using GraphQL is that <strong>API versioning is no longer necessary</strong> 📅❌. GraphQL schemas evolve over time to meet new needs. For example, if the first version of your API returns a field named nameX, and later it needs to be renamed to nameY, all you have to do is:</p><ul><li>Update the GraphQL type</li><li>Add the new field</li><li>Mark the old one as @deprecated</li></ul><p>No need to create v1, v2, v3 versions like we often do with REST.</p><p>So, let’s get our hands dirty and create a project using GraphQL as a BFF for our applications 🧪🎯The architecture of our project will look like this:</p><ul><li>A Spring Boot application exposing a GraphQL server, acting as the <strong>BFF</strong></li><li>Two simple Java apps that will serve as the <strong>data sources</strong> for our GraphQL API</li></ul><p>Let’s code! 💻🔥</p><p>The example project for this GraphQL directed study consists of <strong>three sub-projects</strong>. Why is that? 🤔 Because in modern backend architectures, GraphQL is commonly used as a <strong>BFF — Backend for Frontend</strong>.</p><p>So, the architecture of this POC will include:</p><ul><li>Two microservices:</li><li>One exposes endpoints related to <strong>client profiles</strong></li><li>The other exposes endpoints for <strong>client financial transactions</strong></li><li>One GraphQL API server that acts as the <strong>only and main entry point</strong> for external services or frontend requests 📡</li></ul><p>The two microservices providing data to GraphQL are very simple Spring Boot Java applications. They only expose endpoints, with a mocked database, some DTOs, and a basic service class 🧪.</p><p>The <strong>GraphQL Spring Boot server</strong> contains the entire GraphQL structure, including:</p><ul><li>Schema and query mappings</li><li>FeignClient interfaces to fetch data from the provider services</li><li>DTOs to map the responses</li><li>A service class to orchestrate the calls between GraphQL and the microservices 🔧</li></ul><p>Just to point it out 📝: The build.gradle files for the applications <strong>info-provider-a</strong> and <strong>info-provider-b</strong> use the same dependencies, only: implementation “org.springframework.boot:spring-boot-starter-web” . The <strong>graphql-server</strong> application uses two key dependencies: implementation “org.springframework.boot:spring-boot-starter-graphql” and the implementation “org.springframework.cloud:spring-cloud-starter-openfeign” . These are for enabling GraphQL and consuming the endpoints of the provider services 🔗.</p><p>👉 Pay attention to the application.properties file of each service.<br> These files map the ports of each service to avoid conflicts and startup errors. Also, the graphql-server properties file includes path mappings and logging configuration — so it’s worth checking that out too 🕵️‍♂️</p><p>Here on Medium, I’ll include only the <strong>main GraphQL-related files</strong>. The rest of the project can be found in the <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/graphql-basics">GitHub repository page</a>. 📂🐙</p><p>The file schema.graphqls:</p><pre># available queries<br>type Query {<br>    clientById(id: ID!): ClientProfile<br>    allClients: [ClientProfile]<br><br>    # resolvers for generic queries<br>    clientsByTransactionDate(date: String!): [ClientProfile]<br>    clientsWithMinTransactionTotal(minValue: Float!): [ClientProfile]<br>}<br><br># mapping the java types<br>type ClientProfile {<br>    id: ID<br>    name: String<br>    nationalId: String<br>    birthDate: String<br>    transactions: [TransactionHistory]<br><br>    # resolvers for the clientProfile additional data<br>    totalTransactionAmount: Float<br>    transactionsByType(type: String): [TransactionHistory]<br>}<br><br>type TransactionHistory {<br>    id: ID<br>    clientId: ID<br>    value: Float<br>    transactionDate: String<br>    type: String<br>}</pre><p>The <strong>schema file</strong> is the most important part of GraphQL, because it defines all the types that will be returned by the API and the possible queries 🔍. You can think of it as the <strong>documentation</strong> of your API — similar to how OpenAPI or Swagger works for a traditional REST API 📄.</p><p>In this file, you’ll see:</p><ul><li>Primitive types — like ID, String, Float, etc.</li><li>Custom/composed types — like ClientProfile, TransactionHistory</li><li>And some fields called <strong>resolvers</strong> ⚙️</li></ul><p>The <strong>primitive types</strong> are natively mapped by the framework — just like in Java when you use int, double, etc. One primitive type that gets special treatment is ID. It’s a <strong>special scalar type</strong> used to represent unique identifiers. Although ID is treated as a String by GraphQL, once the value reaches your Java code, it&#39;s automatically converted to its appropriate type — like Long, UUID, or Integer depending on your logic 🧠.</p><p><strong>Custom types</strong> are like objects in any object-oriented programming language 🧱. You define them however you need, to represent the data your API will expose. One important note here: GraphQL <strong>does not know how to map these custom types from Java automatically</strong>. So you need to create <strong>specific mappers</strong> using Spring Boot’s annotation: @SchemaMapping. (I’ll explain this better in the next paragraphs 😉)</p><p>Now let’s talk about <strong>resolvers</strong>. Resolvers in GraphQL are functions that contain the logic to resolve fields with specific rules or data sources. They’re divided into two types:</p><ul><li><strong>Root Resolvers</strong> — fields in the Query type (the input of your API). These are the main entry points for your GraphQL API. In Spring Boot, they are implemented using @QueryMapping 🚪.</li><li><strong>Field Resolvers</strong> — fields inside custom types. These fields <strong>don’t come directly</strong> from the object returned by the query — they need extra logic to be resolved. In Spring Boot, you implement them using @SchemaMapping 🧩.</li></ul><p>The next file is the ClientTransactionQueryResolver:</p><pre>@Controller<br>public class ClientTransactionQueryResolver {<br><br>    private final ClientTransactionAggregationService service;<br><br>    public ClientTransactionQueryResolver(ClientTransactionAggregationService service) {<br>        this.service = service;<br>    }<br><br>    @QueryMapping<br>    public ClientProfile clientById(@Argument Long id) {<br>        return service.getById(id);<br>    }<br><br>    @QueryMapping<br>    public List&lt;ClientProfile&gt; allClients() {<br>        return service.getAll();<br>    }<br><br>    @QueryMapping<br>    public List&lt;ClientProfile&gt; clientsByTransactionDate(@Argument String date) {<br>        LocalDate targetDate = LocalDate.parse(date);<br>        List&lt;TransactionHistory&gt; allTransactions = service.getAllTransactions();<br><br>        Set&lt;Long&gt; clientIdsWithTransactionsOnDate = allTransactions.stream()<br>                .filter(t -&gt; t.transactionDate().equals(targetDate))<br>                .map(TransactionHistory::clientId)<br>                .collect(Collectors.toSet());<br><br>        return service.getAll().stream()<br>                .filter(c -&gt; clientIdsWithTransactionsOnDate.contains(c.id()))<br>                .toList();<br>    }<br><br>    @QueryMapping<br>    public List&lt;ClientProfile&gt; clientsWithMinTransactionTotal(@Argument BigDecimal minValue) {<br>        return service.getAll().stream()<br>                .filter(c -&gt; {<br>                    BigDecimal total = service.getTransactionsByClientId(c.id()).stream()<br>                            .map(TransactionHistory::value)<br>                            .reduce(BigDecimal.ZERO, BigDecimal::add);<br>                    return total.compareTo(minValue) &gt;= 0;<br>                })<br>                .toList();<br>    }<br>}</pre><p>This file is the equivalent of @RestController in a REST API using Spring Boot Web 🌐.</p><p>All the Query type definitions from the schema.graphqls file are mapped here. The link between the query in the schema and the Java method happens <strong>by name</strong> — so if you define a query in schema.graphqls called &quot;getClients&quot;, your @QueryMapping method must have the <strong>same name</strong> and the corresponding @Argument parameter.</p><p>Basically, this file contains the <strong>Java logic that returns the data</strong> to whoever requested it 🧠💡.</p><p>The file next mapping file is the ClientTypeResolver:</p><pre>@Controller<br>public class ClientTypeResolver {<br>    private final ClientTransactionAggregationService service;<br><br>    public ClientTypeResolver(ClientTransactionAggregationService service) {<br>        this.service = service;<br>    }<br><br>    @SchemaMapping(typeName = &quot;ClientProfile&quot;, field = &quot;transactions&quot;)<br>    public List&lt;TransactionHistory&gt; transactions(ClientProfile profile) {<br>        return service.getTransactionsByClientId(profile.id());<br>    }<br><br>    @SchemaMapping(typeName = &quot;ClientProfile&quot;, field = &quot;totalTransactionAmount&quot;)<br>    public BigDecimal totalTransactionAmount(ClientProfile profile) {<br>        return service.getTransactionsByClientId(profile.id())<br>                .stream()<br>                .map(TransactionHistory::value)<br>                .reduce(BigDecimal.ZERO, BigDecimal::add);<br>    }<br><br>    @SchemaMapping(typeName = &quot;ClientProfile&quot;, field = &quot;transactionsByType&quot;)<br>    public List&lt;TransactionHistory&gt; transactionsByType(ClientProfile profile, @Argument String type) {<br>        return service.getTransactionsByClientId(profile.id())<br>                .stream()<br>                .filter(t -&gt; t.type().equalsIgnoreCase(type))<br>                .toList();<br>    }<br>}</pre><p>This next file follows the <strong>same logic</strong> as the previous one, but with a key difference: It maps the <strong>fields inside the custom types</strong> defined in the schema.graphqls file 🧱.</p><p>To connect the logic in your Java code with the GraphQL type, you use the @SchemaMapping annotation. This annotation receives two parameters:</p><ul><li>typeName: the name of the type being mapped</li><li>field: the specific field inside that type you’re handling</li></ul><p>So, it’s like saying: “Hey GraphQL, when someone asks for this field in that type, here’s the logic to use!” 😎</p><p><strong>So let’s go!</strong> 🚀</p><p>To run the entire architecture, we need to follow a few steps, since this project has <strong>three services that must start together</strong>.</p><p><strong>Step one</strong> is to start all of them. To make this easier, we’ll use <strong>Docker Compose</strong> to spin everything up 🐳.</p><p>The Docker Compose command will grab the bootJar files of the three services and deploy them into containers.👉 But for that to work, we first need to generate the bootJar files.</p><p>To create the bootJar files — and here I’m using the structure of my GitHub repository for this project — we need to go into the specific folder where the GraphQL project lives.</p><p>So if you cloned the project properly, the root folder will be Java-Series. Open a terminal in that folder and type:cd graphql-basics , This will take us into the graphql-basics folder.</p><p>Inside that folder, you’ll see a build.gradle script. That script defines a custom Gradle task to build <strong>all</strong> the bootJars for this GraphQL project. So now just run: gradle buildAllBootJar . After that, each sub-project will have a build folder containing the executable we need 🛠️</p><p>Now that we have all the bootJars, let’s use the Dockerfiles and Docker Compose script to start everything together.</p><p>In the <strong>same folder</strong> where you ran the buildAllBootJar command (graphql-basics), just type: docker compose -p graphql-bff -f graphql-bff-docker.yml up -d . This will <strong>build and start</strong> all the containers — and we’re ready to test it! 🧪⚙️</p><p>Here is the Dockerfile for all services:</p><pre>FROM eclipse-temurin:21-jdk<br>WORKDIR /app<br>COPY build/libs/*.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>And here is the docker-compose script:</p><pre>version: &#39;3.8&#39;<br>services:<br>  graphql-server:<br>    build:<br>      context: ./graphql-server<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - info-provider-a<br>      - info-provider-b<br>    networks:<br>      - graphql-net<br><br>  info-provider-a:<br>    build:<br>      context: ./graphql-info-provider-A<br>    ports:<br>      - &quot;8081:8081&quot;<br>    networks:<br>      - graphql-net<br><br>  info-provider-b:<br>    build:<br>      context: ./graphql-info-provider-B<br>    ports:<br>      - &quot;8082:8082&quot;<br>    networks:<br>      - graphql-net<br><br>networks:<br>  graphql-net:</pre><p>To test the GraphQL API, there’s a built-in <strong>GraphQL Playground</strong> included with the Spring GraphQL dependency 🧪🎮. To enable it, we need to configure the following properties in the application.properties file of the graphql-server application: spring.graphql.graphiql.enabled=trueand the spring.graphql.graphiql.path=/graphiql . These properties will enable and expose the GraphQL Playground at the specified path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaV2irJ-9mxFEZCu81TN3A.png" /><figcaption>GraphQL playground</figcaption></figure><p>In the image above, you can see the <strong>GraphQL Playground</strong> being accessed at: 👉 <a href="http://localhost:8080/graphiql">http://localhost:8080/graphiql</a></p><p>You can also see some of the queries and types defined in the schema.graphqls file being executed. Here’s what the UI highlights:</p><ul><li>🔵 <strong>Type Resolvers</strong> — These are used as fields inside the ClientProfile type and are being fetched as part of the query.</li><li>🟡 <strong>Query Resolvers</strong> — These are the main query entries, similar to what a REST endpoint would return.</li><li>🔴 <strong>JSON Response</strong> — One of the responses from the query is shown on the left side, in JSON format.</li></ul><p>✅ Now we have a fully configured GraphQL as BFF project with spring boot.</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography:</h3><p><a href="https://docs.spring.io/spring-graphql/reference/boot-starter.html">Boot Starter :: Spring GraphQL</a></p><p><a href="https://graphql.org/community/tools-and-libraries/?tags=server_java-kotlin-android">Server and Java / Kotlin | Tools and Libraries | GraphQL</a></p><p><a href="https://www.graphql-java.com/tutorials/getting-started-with-spring-boot">Tutorial with Spring for GraphQl | GraphQL Java</a></p><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/graphql-basics">Java-Series/graphql-basics at master · AugustoKlaic/Java-Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d649f853b477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Build]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-build-c8c76edd3a86?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c76edd3a86</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[build]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 20:23:07 GMT</pubDate>
            <atom:updated>2025-06-24T20:23:34.335Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Gradle</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*0GdptS1LUUMmbcfY.png" /></figure><p>So let’s talk about <strong>builds in Java</strong> 🛠️.</p><p>Build tools are an essential part of Java development. Today, the most popular and widely used build tools are <strong>Maven</strong> and <strong>Gradle</strong>. There are others like <strong>Ant</strong>, but honestly, I’ve never worked on a project that used it 😅.</p><p>These build tools come packed with several functionalities. The most common one is <strong>dependency management</strong>. Java development nowadays relies on a ton of different libraries, and we can’t go around downloading .jar files manually and importing them into the project one by one. That would be super time-consuming and a nightmare to maintain everything up to date 😵‍💫.</p><p>Besides that, build tools can:</p><ul><li>Run tests ✅</li><li>Generate executable files 🧪</li><li>Move files 🗃️</li><li>Create tasks for CI/CD pipelines ⛓️</li><li>Execute commands from the terminal 💻</li><li>Define environment variables 🌱</li><li>Manage versions 🔢<br> …and much more!</li></ul><p>All three build tools mentioned here aim for the same goal, but they differ in the way you write their configurations.</p><ul><li><strong>Gradle</strong> uses the <strong>Groovy</strong> language to write scripts (you can also use Kotlin DSL, but let’s stick with Groovy for now).</li><li><strong>Maven</strong> and <strong>Ant</strong>, on the other hand, use an <strong>XML-based structure</strong> 📄.</li></ul><p>This text will focus on <strong>Gradle</strong>, since it’s the one I’ve used the most in the projects I’ve worked on 💪.</p><h3>Gradle’s Structure 📦</h3><p>Gradle’s syntax is organized into <strong>blocks of code and variables</strong>. Let’s go through each part and explain some of its features.</p><h4>Starting with the <strong>syntax</strong>:</h4><p>It’s written in a language called <strong>Groovy</strong>. Groovy is much more concise than Java and is <strong>dynamically typed</strong>. When used in pipelines and build scripts (like in Gradle or Jenkins), it might look like a declarative language — <strong>DSLs (Domain-Specific Languages)</strong> — where the code feels more descriptive than imperative ✍️.</p><p>Groovy is object-oriented and has full <strong>interoperability with Java</strong>, meaning you can mix Groovy and Java code together seamlessly 🤝. This is great when you need flexibility in your builds or want to reuse existing Java logic.</p><h3>The plugins block 🔌</h3><p>Inside this block, <strong>extra functionalities</strong> are added to the project — things like <strong>language support</strong> (Java, Kotlin), <strong>framework support</strong> (Spring Boot), <strong>dependency management</strong>, <strong>JAR/WAR packaging</strong>, and more.</p><p>Every plugin included brings along new automated tasks and default configurations to make your life easier when building, packaging, and testing the project 🧙‍♂️✨.</p><p>There are many types of plugins for different objectives:</p><h4>🧱 Base Plugins</h4><p>Examples: java, war<br> These add basic build capabilities:</p><ul><li>java: Enables compiling a Java project, running tests, and generating .jar files 📦</li><li>war: Adds support for generating .war files to be deployed on a web server like Tomcat 🌐</li></ul><h4>🌱 Spring Plugins</h4><p>Examples: org.springframework.boot, io.spring.dependency-management<br> These bring Spring Boot-specific magic:</p><ul><li>org.springframework.boot: Allows running your app with bootRun, packaging it with bootJar (a.k.a. fat JAR) 🏃‍♂️</li><li>io.spring.dependency-management: Automatically manages compatible dependency versions based on the Spring Boot version you&#39;re using — no more version headaches! 😌</li></ul><h4>🧪 Test and Code Quality Plugins</h4><p>Examples: jacoco, checkstyle<br> These keep your code clean and tested:</p><ul><li>jacoco: Generates code coverage reports 📊</li><li>checkstyle: Enforces code formatting rules (indentation, line breaks, etc.) ✏️</li></ul><p>These are just <strong>some of the most popular plugins</strong> used in Java projects. As you can see, each plugin serves a specific purpose and adds its own set of tasks for you to use — and of course, there are <em>many</em> more out there waiting to be explored 🔍😉.</p><h3>📌 Variables and Properties</h3><p>In a Gradle script, <strong>properties</strong> can be defined <em>outside</em> any block of code. These are essentially <strong>global variables</strong>, and they help define characteristics of the final generated executable 🎯.</p><p>For example:</p><ul><li><strong>group</strong>: Defines the <strong>namespace</strong> of the project. Usually, it&#39;s the base package of your code — something like com.yourname.project. This is useful for identifying your artifact inside repositories like <strong>Maven Central</strong> or <strong>JFrog Artifactory</strong> 🏷️.</li><li><strong>version</strong>: Sets the <strong>current version</strong> of your project. This version will be used in the name of the generated .jar or .war file. Examples: 1.0.0, 0.0.1-SNAPSHOT, 1.0.0-RC1, etc. 📦</li><li><strong>sourceCompatibility</strong>: Specifies the <strong>minimum Java version</strong> your code is compatible with. For example, if you set sourceCompatibility = 17, Gradle will compile the project using Java 17 ☕This is super helpful for keeping things compatible and avoiding surprises in production!</li></ul><p>This part of the Gradle script doesn’t have a strict standard on what you <em>must</em> declare. You’re free to create <strong>as many variables as needed</strong> to suit your project’s needs 🙌</p><h3>📚 The repositories block</h3><p>In this code block, you define <strong>where Gradle should look for your project’s dependencies</strong>. Without it, Gradle won’t find <em>any</em> external libraries 😅.</p><p>One of the most common repositories used is <strong>mavenCentral()</strong>, the most popular public repository in the Java world. It hosts thousands of <strong>open-source libraries and frameworks</strong> that you can freely import into your project 🚀.</p><p>But you’re not limited to just Maven Central! You can also add:</p><ul><li><strong>Private repositories</strong>, like <strong>JFrog Artifactory</strong>, <strong>Nexus</strong>, etc. 🔒</li><li><strong>Internal repositories</strong> (used a lot in enterprise environments) 🏢</li><li><strong>mavenLocal()</strong>, which points to the .m2 folder on your machine — useful when you publish JARs locally for testing 🧪</li></ul><p>🧠 <strong>Pro tip</strong>:<br> You can add <strong>multiple repositories</strong>, and Gradle will search for dependencies <strong>in the order</strong> they are declared. So be mindful of that ordering — the first match it finds, it stops searching! 🕵️‍♂️</p><h3>📦 The dependencies block</h3><p>This is the part of the script where you declare <strong>all the external dependencies</strong> your project needs. Gradle will download them from the <strong>repositories</strong> you defined earlier 📥.</p><p>Each dependency line follows a standard format: scope “group:artifact:version”</p><h4>🎯 The scope defines where and how the dependency will be used in your project.</h4><p>Here are the most common scopes:</p><ul><li><strong>implementation</strong>: Used for dependencies in your <strong>main code</strong>. It <em>doesn&#39;t</em> expose the dependency to other projects that depend on yours — mais seguro! 🔒</li><li><strong>api</strong>: Similar to implementation, but <strong>exposes</strong> the dependency to projects that use your module. Good when you’re building shared libraries 📚</li><li><strong>compileOnly</strong>: Used only at <strong>compile time</strong> — the dependency <strong>won’t be packaged</strong> and <strong>won’t be available at runtime</strong>. Example: annotations provided by your IDE or SDKs 👨‍🏫</li><li><strong>runtimeOnly</strong>: Opposite of compileOnly: only available during <strong>execution</strong>, not during compilation 🏃</li><li><strong>annotationProcessor</strong>: Used for annotation processor tools that run during compilation, like Lombok or MapStruct ✨</li><li><strong>testImplementation &amp; </strong><strong>testRuntimeOnly</strong>:Same concepts as above, but specifically for <strong>tests</strong> (JUnit, Mockito, etc.) 🧪</li></ul><h4>🧭 What about group:artifact:version?</h4><p>This part is known as the <strong>dependency coordinate</strong>. It uniquely identifies the .jar Gradle needs to download. It’s basically the same structure you used when declaring your project&#39;s own group and version earlier — just applied to external libs now 🔍.</p><h3>⚙️ The tasks block</h3><p>In a Gradle build script, one of the most powerful features is the ability to <strong>create or configure tasks</strong>. A <strong>task</strong> is essentially a step in the build process — something that Gradle can execute 🏃‍♂️.</p><p>You can create your own custom tasks to do whatever you need, but Gradle already comes with several <strong>built-in tasks</strong>, such as:</p><ul><li>build 🏗️</li><li>clean 🧹</li><li>assemble 🧰</li><li>check ✅</li><li>test 🧪<br> ...and many more!</li></ul><p>Plugins you apply in your build.gradle also bring their own <strong>pre-configured tasks</strong>. For example:</p><ul><li>The <strong>Jacoco plugin</strong> adds tasks for code coverage reports 📊</li><li>The <strong>Spring Boot plugin</strong> adds tasks like bootRun, bootJar, etc. 🚀</li></ul><p>These tasks are actions that Gradle can perform — like compiling code, running tests, packaging a JAR, running the app, moving files, printing something on the console… whatever you need 💻</p><p>You can:</p><ul><li><strong>Create brand-new tasks</strong> 🔧</li><li>Or <strong>configure existing ones</strong>, like a kind of override pattern 🔁</li></ul><p>Let’s take the built-in Gradle task test as an example: Even if you don’t explicitly declare it in your script, it already exists — it’s automatically added when you apply the java plugin. But if you <strong>add a </strong><strong>test {} block</strong> to your build.gradle, you can customize its behavior. For instance:</p><pre>test {<br>    useJUnitPlatform()<br>}</pre><p>Now, your test task will run using the <strong>JUnit Platform</strong>, thanks to your custom configuration 👨‍🔬</p><p>When you create a task with a name that doesn’t match any standard Gradle task, it becomes a <strong>new custom task</strong>. And like we said earlier — you can make it do pretty much <em>anything</em>! From file manipulation to custom shell commands.🤘</p><h3>🧠 The Gradle DSL</h3><p>Gradle executes each block in the script using its <strong>DSL (Domain-Specific Language)</strong>. This DSL is built on top of objects internally registered by Gradle. So, when you create a task with a certain name, Gradle will <strong>register it internally</strong>. If you use a name that already exists, Gradle will reference the existing task — and <strong>override it</strong> if needed 🔁.</p><p>Now, the behavior is <strong>a bit different</strong> for other blocks, like dependencies and repositories. That’s because these aren’t tasks — they’re actually <strong>methods registered by Gradle</strong>. When Gradle executes these blocks, it <strong>translates them into methods</strong> that receive a <strong>Groovy closure</strong> — a little chunk of code passed as an argument, very Groovy-style ✨.</p><p>The Gradle DSL exposes all those <strong>properties</strong> (methods, containers, and tasks) as <strong>code blocks</strong>, which are delegated to internal Gradle objects. Although they may look similar in the script, they’re <strong>not the same thing</strong> under the hood 🧩</p><h3>📂 build.gradle, settings.gradle, and gradle.properties</h3><p>In a Gradle project, besides the main build.gradle script (which we’ve been focusing on so far), you’ll also find two other important files: settings.gradle and gradle.properties. Let’s break it down:</p><p><strong>build.gradle</strong> 📜This is the <strong>main configuration file</strong>. It defines:</p><ul><li>Project dependencies and where to find them 🔗</li><li>Language/version settings (like Java version) ☕</li><li>Script versions and custom tasks ⚙️This is where the build logic lives!</li></ul><p><strong>settings.gradle</strong> 🧭 This file defines the <strong>build context</strong>. It can:</p><ul><li>Set the <strong>project’s name</strong> 🏷️</li><li>Include <strong>sub-projects</strong> (a.k.a. modules) 🧱</li><li>Define global build settings (like cache configs) 🧠 If you don’t create this file, Gradle will just assume the folder name as your project name.</li></ul><p><strong>gradle.properties</strong> ⚙️ This file works like an application.properties, but for your <strong>build</strong>.</p><ul><li>It’s used to define <strong>reusable variables and global properties</strong> across the project.</li><li>It can even override values from your local .gradle folder (where Gradle stores some internal configs and caches).</li></ul><p>🎉 Now that we’ve dissected and understood the full <strong>Gradle structure</strong>, it’s time to get our hands dirty and <strong>code a personalized build script</strong>! 💻🔥</p><h3>🧪 Putting it into practice: the example project</h3><p>To demonstrate how to create a real build script and test its functionalities, we’ll use a <strong>demo application</strong> — the same one used earlier in this Java series 👨‍💻.</p><p>It’s a simple app that:</p><ul><li>Performs basic <strong>math operations</strong> ➕➖</li><li>Exposes a <strong>REST endpoint</strong> 🌐</li><li>Includes some <strong>unit tests</strong> to validate behavior ✅</li></ul><p>The full project is available on the <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/build-gradle"><strong>GitHub repository</strong></a>.</p><p>Since the main goal of this text is to <strong>explore and test Gradle’s features</strong>, we’ll be using the three key Gradle files we discussed earlier:</p><ul><li>build.gradle</li><li>settings.gradle</li><li>gradle.properties</li></ul><p>⚠️ <strong>Important note</strong>: This section will focus only on the <strong>Gradle part</strong>. For example, in the checkstyle task, an external XML config file is used — but I won’t include it here in the text to keep things focused. No worries though — that file will also be available in the GitHub repo 📁🔍</p><p>The build.gradle file looks like this:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;jacoco&#39;<br>    id &#39;checkstyle&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.5.0&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.buildgradle&#39;<br>version = &#39;1.0.0&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br><br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>test {<br>    useJUnitPlatform()<br>    testLogging {<br>        events &quot;passed&quot;, &quot;skipped&quot;, &quot;failed&quot;<br>    }<br>}<br><br>jacocoTestReport {<br>    dependsOn test<br>    reports {<br>        xml.required = true<br>        html.required = true<br>    }<br><br>    afterEvaluate {<br>        classDirectories.setFrom(<br>                files(classDirectories.files.collect {<br>                    fileTree(dir: it, exclude: [<br>                            &#39;**/dto/**&#39;,<br>                            &#39;**/BuildGradleApplication.class&#39;<br>                    ])<br>                })<br>        )<br>    }<br>}<br><br>checkstyle {<br>    toolVersion = &#39;10.12.3&#39;<br>    configFile = file(&quot;$projectDir/checkstyle.xml&quot;)<br>}<br><br>build {<br>    dependsOn jacocoTestReport<br>    dependsOn checkstyleMain<br>}<br><br>tasks.register(&#39;hello&#39;) {<br>    group = &#39;User tasks&#39;<br>    description = &#39;Print Hello Gradle&#39;<br>    doLast {<br>        println &#39;Hello Gradle!&#39;<br>    }<br>}<br><br>tasks.register(&#39;buildJarForDeploy&#39;, Jar) {<br>    group = &#39;Deployment&#39;<br>    description = &#39;Generate executable JAR for deploy&#39;<br><br>    dependsOn hello<br>    dependsOn build<br>    dependsOn bootJar<br><br>    archiveBaseName.set(&quot;gradle-project&quot;)<br>    from sourceSets.main.output<br><br>    doLast {<br>        def jarFile = archiveFile.get().asFile<br>        def targetDir = file(&quot;deploy&quot;)<br>        targetDir.mkdirs()<br>        copy {<br>            from jarFile<br>            into targetDir<br>        }<br>        println &quot;JAR copiado para ${targetDir.absolutePath}&quot;<br>    }<br>}</pre><h3>🔍 Let’s take a look at the build.gradle script</h3><p>Below is an <strong>example of a Gradle build script</strong>. Of course, real-world projects often include a lot more configurations and tasks, but this example should cover a good portion of what usually happens in real scenarios 🚧📦</p><h4>🧾 Defining the scenario:</h4><p>The script should be able to:</p><ul><li>📥 <strong>Download dependencies</strong></li><li>🧠 <strong>Compile the project</strong></li><li>🧪 <strong>Run tests</strong></li><li>🏗️ <strong>Build the executable file</strong> (.jar)</li></ul><p>The first part of the script follows exactly what we explained earlier about Gradle blocks. It’s composed of:</p><ul><li>✅ <strong>Plugins</strong>: spring-boot, java, jacoco, and checkstyle</li><li>📚 <strong>Repositories</strong>: mavenCentral() to fetch dependencies</li><li>📦 <strong>Dependencies</strong>: such as spring-boot-starter, spring-boot-starter-test, and junit</li><li>⚙️ <strong>Java version setting</strong>: defined as version 21</li></ul><p>Continuing with the script, the next section focuses on <strong>task definitions</strong>. This can include:</p><ul><li>✨ Creating <strong>new tasks</strong></li><li>🔁 Or configuring <strong>predefined Gradle tasks</strong> (like we discussed earlier)</li></ul><p>Both approaches allow you to customize how your build process behaves — whether it’s changing how tests are run, generating reports, moving files, or whatever you need to automate during the build process 💪</p><h4>🔧 Configured tasks in the script</h4><p>Here’s the rundown on the tasks configured in our example Gradle script. At the start of each section, you’ll find the exact command to run the task in your terminal — just navigate to your project folder and type it in! 🖥️💨</p><p>gradle test:🧪Simple and direct — this one runs <em>all</em> the tests in your application. We also configured the test task to use <strong>JUnit Platform</strong> and log every event that happens during testing: whether a test passes, fails, or gets skipped. So you get the full picture right in your terminal — no mysteries here! 🔍✨</p><p>gradle jacocoTestReport :📊This task depends on the test task — meaning it’ll always run your tests first to gather coverage data, then generate the coverage report. Inside the task, the reports block tells Jacoco what kind of reports to produce:</p><ul><li>XML report (for integration with other tools and frameworks)</li><li>HTML report (for humans to browse and drool over coverage stats) 😎</li></ul><p>The afterEvaluate block makes sure Jacoco <strong>waits</strong> for all tests to finish <em>before</em> it starts crunching coverage numbers. The classDirectories block is the bouncer that decides which classes get analyzed — including everything except what’s in the exclude list. At the end, you get a sweet, detailed test coverage report to brag about! 🎉📈</p><p>gradle checkstyleMain: ✏️Here, things get a little trickier. We configure a generic checkstyle block, but the actual tasks you run are checkstyleMain and checkstyleTest. These guys scan your code for style rules — indentation, spacing, naming conventions and more. The style rules themselves live in an XML file called checkstyle.xml, lurking somewhere in your project folder. This file needs to follow a strict format and rule order, so check the <a href="https://checkstyle.sourceforge.io/index.html">Checkstyle plugin </a>docs to avoid headaches! 🤓📚 If your code breaks any rule, these tasks will throw errors — no style rebels allowed! 🚫👩‍🎨</p><p>gradle build: 🏗️ it compiles your source code, runs all tests, and builds the executable .jar (or .war) file ready for deployment. In our example, build depends on both checkstyle and jacocoTestReport. That means it won’t let you build if your code style sucks or if tests are failing — a solid gatekeeper to keep quality high and bugs low! 🔒✅</p><h4>🆕 New tasks in the script</h4><p>Here, I’ll explain the <strong>newly created tasks</strong> in our example Gradle script. To run any of these, go to the project’s folder in your terminal and type the command at the beginning of each paragraph below 👇</p><p>gradle hello :👋This is a simple example of a <strong>user-defined task</strong>. When executed, it just prints: <em>hello Gradle!</em> in the terminal. That’s it — minimal but useful to understand how tasks work. You can also <strong>call this task inside other tasks</strong>, and the message will be printed during their execution. We added a group and description to this task to help organize it in Gradle menus inside IDEs like IntelliJ — so things stay nice and tidy in the UI 🧼🧑‍💻</p><p>gradle buildJarForDeploy : 📦This task is <strong>much more common in real-world projects</strong>. It’s especially useful in CI/CD pipelines, where you need to:</p><ul><li>Build an executable file (usually a .jar)</li><li>Move it to another folder (e.g., a Docker volume) or send it to an artifact repository like Artifactory or Nexus 🚀</li></ul><p>In our example, this task <strong>depends on</strong>:</p><ul><li>hello (just for fun 😄)</li><li>build (which compiles and tests)</li><li>bootJar (which creates the Spring Boot executable JAR)</li></ul><p>Because of those dependencies, this task indirectly relies on <em>all other tasks</em> we’ve configured — great to show <strong>task reusability</strong> in action 🧩</p><p>Inside the task:</p><ul><li>We use archiveBaseName.set(...) to <strong>rename the JAR</strong> being created.</li><li>The from command tells Gradle <strong>which files</strong> to include in the JAR — in this case, all .class files from the output folder.</li></ul><p>Then we get to doLast { ... } — this block runs <strong>after</strong> the JAR is generated.<br> Here’s what it does:</p><ol><li>Gets the generated JAR file 📄</li><li>Creates a deploy/ directory if it doesn’t exist 📁</li><li>Copies the JAR into that folder</li><li>Prints a message in the terminal with the path of the copied file — so you know where your shiny new JAR ended up! 🗂️✨</li></ol><h3>🧩 Complementary Gradle files</h3><p>The Java-series project I’ve been building is structured as a <strong>multi-module project</strong> in Gradle. That means it has a <strong>root project</strong> and multiple <strong>child modules</strong> (a.k.a. subprojects).</p><p>Each sub-module has its own build.gradle file with its own set of dependencies, tasks, configurations, and so on — allowing each piece of the system to be modular and self-contained 🧱</p><p>To organize and manage a multi-module setup like this, we use the following files:</p><h4>🧭 The settings.gradle file</h4><pre>// child settings.gradle file<br><br>rootProject.name = &quot;java-series&quot;<br>buildCache {<br>    local {<br>        enabled = true<br>        directory = &quot;${rootDir}/.gradle-build-cache&quot; <br>        removeUnusedEntriesAfterDays = 2<br>    }<br>}<br><br>// root settings.gradle file<br><br>rootProject.name = &quot;java-series&quot;<br>include &#39;build-gradle&#39;</pre><p>The settings.gradle file defines the <strong>context of the build</strong>. It tells Gradle which module is the <strong>main project</strong>, which ones are its <strong>submodules</strong>, and can also include <strong>global configurations</strong> like caching, build environment settings, and more. To wire everything up correctly:</p><ul><li>In each <strong>child module</strong>, you should define rootProject.name</li><li>In the <strong>root project</strong>, you use the include command to point to each child module (as shown in the example above)</li></ul><p>Once that’s done, Gradle will know how to link all modules together and build them in the correct order 🧱⚙️</p><p>💡 Configuration Scope: You can define configurations in either the <strong>root</strong> or the <strong>child module’s</strong> settings.gradle file:</p><ul><li>✅ <strong>Defined in the root</strong> → becomes available to <strong>all</strong> submodules</li><li>📦 <strong>Defined in a submodule</strong> → available <strong>only within that module</strong></li></ul><p>In our example, I added a <strong>Gradle cache configuration</strong> — but just for the subproject that focuses on the build logic (to keep things isolated and modular). In our gradle cache in the example there are some properties like:</p><ul><li>enabled = true → turns on the local build cache 💡</li><li>directory → specifies <strong>where</strong> on the machine the cache data will be stored 🗂️</li><li>removeUnusedEntriesAfterDays → does exactly what it says: clears out old cache data after a few days 🧹🕒</li></ul><p>This helps Gradle skip unnecessary work by reusing previously built outputs — speeding up your builds without relying on remote servers. Fast, clean and self-contained 🚀💼</p><h4>🧪 Testing the Gradle Cache</h4><p>Just to point it out — in order to <strong>build with cache enabled</strong>, you need to run the command: gradle build — — build-cache --info .</p><p>This will show detailed output in the terminal, including which <strong>build phases</strong> are being executed and whether <strong>cache is being used or not</strong>. 🕵️ On the <strong>first run</strong>, Gradle will just execute everything normally and <strong>create the cache</strong> for future use — so don’t expect any reused tasks right away.</p><p>Now, let’s test if the cache is really working with the command: gradle clean --no-build-cache , this will <strong>delete all generated build files</strong> (like build/ folders), but <strong>preserve the cache</strong> itself. Then run: gradle build --info , since the original build files are gone but the <strong>cache is still available</strong>, Gradle will try to <strong>reuse whatever it can</strong> from the previous run.</p><p>✅ If everything is working as expected, the terminal logs will show that <strong>some tasks are being loaded from the cache</strong> — speeding things up and skipping unnecessary work. 🧙‍♂️💨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*IIsWbSURYUhyXRILtPriZA.png" /><figcaption>task using cache and task not using cache</figcaption></figure><h4>⚙️ The gradle.properties file</h4><pre>org.gradle.caching=true</pre><p>The gradle.properties file works just like a regular *.properties file in a Java application — think of it as Gradle’s way of handling environment-level config. 🧪📂 It’s a place where you can define <strong>global variables</strong> and configuration values that will be available <strong>across all Gradle files and modules</strong> in your project.</p><p>Common use cases include:</p><ul><li>Defining the Java version (javaVersion=21)</li><li>Centralizing library versions (springBootVersion=3.2.0)</li><li>Adding environment flags (e.g., env=dev, ci=true)</li></ul><p>This helps keep your build scripts <strong>cleaner</strong>, <strong>easier to maintain</strong>, and more <strong>consistent</strong> across modules — no more copying and pasting values everywhere! ✂️📦♻️</p><p>✅ Now we have a fully configured gradle build for a java project with spring boot and with gradle cache for boosting build performance.</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography</h3><p><a href="https://www.baeldung.com/gradle-building-a-java-app">Building a Java Application With Gradle | Baeldung</a></p><p><a href="https://checkstyle.sourceforge.io/index.html">Checkstyle 10.26.0 — checkstyle</a></p><p><a href="https://docs.gradle.org/current/userguide/jacoco_plugin.html">The JaCoCo Plugin</a></p><p><a href="https://docs.gradle.org/current/userguide/build_cache.html">Build Cache</a></p><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/build-gradle">Java-Series/build-gradle at master · AugustoKlaic/Java-Series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c76edd3a86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Caching]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-caching-74b35d9507b3?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b35d9507b3</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 19:29:04 GMT</pubDate>
            <atom:updated>2025-06-12T11:11:38.202Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Redis</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nCA97CERr8klpQg3" /></figure><p>🚀 <strong>Let’s talk about a powerful strategy to boost system performance nowadays: caching!</strong></p><p>Caching is all about storing frequently accessed data in a fast-access, volatile database — though it can also be configured to persist data if needed. The idea is simple: if your system is constantly hitting the same data, why not make that access way faster?</p><p>🛤️ In a typical system flow, when a request comes in (through an HTTP call, a message broker, etc), it usually passes through a service layer that does some validations, then moves to a repository layer that talks to the database, fetches the info, and sends everything back up the chain to the requester.</p><p>📈 Now imagine this whole process happening <strong>millions of times</strong>, for <strong>millions of users</strong>. Naturally, system latency shoots up. That’s where caching comes in to save the day.</p><p>💡 When caching is enabled, the first time a piece of data is accessed, it follows the regular path — all the way to the database. But after that, the data gets stored in an <strong>in-memory cache</strong>, and any future requests fetch it directly from there. Much faster!</p><p>Why is this better? Because cache databases are:</p><ul><li>⚡ Faster (they run in memory),</li><li>💾 Lighter (they store less data),</li><li>💸 Cheaper (they save on expensive DB queries),</li><li>🚪 And they free up your main database to handle more critical operations.</li></ul><p>🧰 There are tons of caching solutions out there, but in this text, we’re going to focus on <strong>Redis</strong>.</p><p>📚 <strong>Redis</strong> stands for <strong>REmote DIctionary Server</strong>:</p><ul><li><em>Remote</em> — because Redis runs as a standalone server, accessible over the network.</li><li><em>Dictionary</em> — because it stores data as key-value pairs.</li><li><em>Server</em> — because it listens for connections and processes commands (usually over TCP).</li></ul><p>🔥 Redis is super popular in cloud-native architectures today due to its blazing-fast performance, low latency, thread safety, and clustering capabilities. And Redis isn’t just for caching! You can also use it as: a lightweight NoSQL database, a message broker, a session store, and much more…</p><p>⚠️ Just keep in mind: Redis runs in memory (RAM), so if you shut it down, your data’s gone — unless you configure it to persist to disk (via snapshots or AOF).</p><p>👨‍💻 So, in this tutorial, I’ll build a simple Java application using Redis for caching. We’ll:</p><ol><li>Spin up a Redis container using Docker,</li><li>Create a sample Java project,</li><li>Connect our app to the Redis server.</li></ol><p>Let’s code! 😎 Check on my <a href="https://github.com/AugustoKlaic/Java-Series/tree/master/redis-cache">Github repo</a> for any questions!</p><p>🐳 <strong>To start, we need to set up our Redis server using Docker.</strong></p><p>If you’re using Spring Boot, it’s not strictly necessary — Spring can automatically spin up a local Redis instance when you add the dependency org.springframework.boot:spring-boot-starter-data-redis to your build script.</p><p>🤓 But for learning purposes, I’m going to use an external Redis instance via Docker.</p><p>Create a Docker Compose file named redis-server-docker.yml with the script below:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  redis:<br>    image: redis:alpine<br>    container_name: redis<br>    ports:<br>      - &quot;6379:6379&quot;</pre><p>💾 Save the file to a folder of your choice. After that, open a terminal in that folder and run the Docker build command: docker compose -p redis-server -f redis-server-docker.yml up -d .</p><p>🐋 Docker should now be up and running! This script is super simple — it just pulls the Redis image, gives the container a name, and maps the default port so it can be accessed externally.</p><p>📦 Now let’s jump to the build.gradle file. We’ll need to add a couple of dependencies to use Redis with Spring Boot.</p><p>For this example, I added spring-boot-starter-web and spring-boot-starter-data-redis to my build.gradle:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.5.0&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.rediscache&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-redis&#39;<br><br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p>🔧 After adding the Gradle dependencies, let’s configure our Java app to connect to the external Redis instance. To do that, open the application.properties file and add the following settings:</p><pre>spring.application.name=redis-cache<br>spring.cache.type=redis<br>spring.data.redis.host=localhost<br>spring.data.redis.port=6379</pre><p>🛠️ This will set the name of the application and define the type of cache Spring Boot will use — in this case, Redis. But keep in mind, there are many other cache options already pre-configured and supported by Spring.</p><p>📍 Set the application host — since Redis will be running on the same machine, you can just use localhost. If it’s running in the cloud, just replace it with the cloud IP address.</p><p>🔌 Then, configure the port — we’ll use the default Redis port, which was already set in the Docker script.</p><p>💻 Now that the configs are done, let’s create the Java app.<br> For the sake of simplicity, I’m going to put all the classes in one code snippet to keep things practical.</p><p>The structure is pretty straightforward:</p><ul><li>a <strong>controller</strong> to expose the endpoints,</li><li>a <strong>service</strong> to fetch the data,</li><li>and a mock “database” represented by a map</li><li>and a domain class.</li></ul><p>📦 Check out the code snippet below:</p><pre>@EnableCaching<br>@SpringBootApplication<br>public class RedisCacheApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(RedisCacheApplication.class, args);<br>    }<br>}<br><br>@RestController<br>@RequestMapping(&quot;/person&quot;)<br>public class PersonController {<br>    private final PersonService service;<br><br>    public PersonController(PersonService service) {<br>        this.service = service;<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public Person getById(@PathVariable(&quot;id&quot;) Long id) {<br>        return service.findById(id);<br>    }<br><br>    @GetMapping<br>    public List&lt;Person&gt; getAll() {<br>        return service.findAll();<br>    }<br><br>    @PostMapping<br>    Long cratePerson(@RequestBody Person person) {<br>        return service.createPerson(person);<br>    }<br>}<br><br>@Service<br>public class PersonService {<br>    private static final Map&lt;Long, Person&gt; PERSONS_SIMULATED_DATABASE = new HashMap&lt;Long, Person&gt;() {<br>        {<br>            put(1L, new Person(1L, &quot;carlos&quot;, &quot;carlos@email.com&quot;));<br>            put(2L, new Person(2L, &quot;rafael&quot;, &quot;rafael@email.com&quot;));<br>            put(3L, new Person(3L, &quot;john&quot;, &quot;john@email.com&quot;));<br>            put(4L, new Person(4L, &quot;alfred&quot;, &quot;alfred@email.com&quot;));<br>            put(5L, new Person(5L, &quot;peter&quot;, &quot;peter@email.com&quot;));<br>        }<br>    };<br><br>    @Cacheable(&quot;persons-by-id&quot;)<br>    public Person findById(Long id) {<br>        System.out.println(&quot;Searching product of id: &quot; + id);<br>        simulateLatency();<br>        return PERSONS_SIMULATED_DATABASE.get(id);<br>    }<br><br>    @Cacheable(&quot;persons-all&quot;)<br>    public List&lt;Person&gt; findAll() {<br>        System.out.println(&quot;Listing all persons...&quot;);<br>        simulateLatency();<br>        return PERSONS_SIMULATED_DATABASE.values().stream().toList();<br>    }<br><br>    @CacheEvict(value = &quot;persons-all&quot;, allEntries = true)<br>    public Long createPerson(Person person) {<br>        PERSONS_SIMULATED_DATABASE.put(person.id(), person);<br>        return person.id();<br>    }<br><br>    private void simulateLatency() {<br>        try {<br>            Thread.sleep(2000);<br>        } catch (InterruptedException e) {<br>            throw new RuntimeException(e);<br>        }<br>    }<br>}<br><br>public record Person(Long id, String name, String email) implements Serializable {<br>}</pre><p>☕ The Java application is pretty simple — it’s just a basic CRUD. It can get all the data, get one item by ID, or create new entries. Nothing complex here, but there are a few important points to highlight:</p><p>⚠️ For Redis caching to work, you need to annotate your main class with @EnableCaching.</p><p>🧠 For every method where you want to <strong>add data to the cache</strong>, you’ll need to annotate it with @Cacheable. This annotation can take some parameters like value, key, etc. If you&#39;re just using the value parameter, you can pass a simple string — like I did in the getById and getAll methods above.</p><p>🧹 For every method where you want to <strong>invalidate the cache</strong>, annotate it with @CacheEvict. This one also accepts parameters, such as value and allEntries. In the example above (the create method), I’m invalidating the cache used in the findAll method — which I named &quot;persons-all&quot;. So here, the value tells which cache should be cleared, and allEntries = true means we’re invalidating <strong>all the entries</strong> in that specific cache.</p><p>⚙️ The rest is all auto-managed by Spring Boot’s Redis configuration.<br> You can customize it further by adding more properties to your application.properties, or by creating custom configuration beans — like in the example below:</p><pre>@Configuration<br>public class RedisConfig {<br>    @Bean<br>    public RedisCacheConfiguration cacheConfiguration() {<br>        return RedisCacheConfiguration.defaultCacheConfig()<br>                .entryTtl(Duration.ofMinutes(5)); // expire in 5 min<br>    }<br>}</pre><p>⏱️ This configuration class sets the <strong>time-to-live (TTL)</strong> for the data stored in the Redis cache. When 5 minutes have passed, all the cached data will be automatically deleted — unless it’s updated by another request.</p><p>📦 But for this short Redis cache example, I think that’s more than enough to illustrate the concept.</p><p>🧪 Just to prove that the application is actually using the cache, take a look at the screenshots below.</p><p>We added a small method called simulateLatency() in the project, which forces a 2-second delay when retrieving data. This delay happens only on the <strong>first call</strong> to the endpoint. From the second call onwards, the response comes straight from the cache — no delay at all! 🚀</p><ul><li>Calling getById endpoint first time:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*S8EZUMO4hPrWpYXnpYf-6g.png" /><figcaption>getById endpoint called for the first time</figcaption></figure><ul><li>Calling getById endpoint second time:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*5HhJaA7y4_3w9KUTLuXspg.png" /><figcaption>getById endpoint called for the second time</figcaption></figure><ul><li>Calling getAll endpoint first time:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*X1uUjGl3EVJnnDrWFF-Zzg.png" /><figcaption>getAll endpoint called for the first time</figcaption></figure><ul><li>Calling getAll for the second time:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*AXbzK15ppfZacjE_fdOLFQ.png" /><figcaption>getAll endpoint called for the second time</figcaption></figure><p>🔍 We can also check directly inside the Redis container to confirm that the data was saved correctly.</p><p>To do that, open a terminal and run: docker ps. This will list all the running containers. Locate the one running Redis and grab its name.</p><p>🛠️ Now, to enter the container, type: docker exec -it redis sh . In my case, the container name is redis, but replace it with whatever name shows up for you.</p><p>Once inside the container, let’s open the Redis CLI by typing: redis-cli .📍 Now you’re inside the Redis console — and we can take a look at the cache data we’ve saved.</p><p>To list all the keys currently stored, run: keys * . Redis will return all the keys being used in the cache. (Remember: Redis is a key-value database, so these are your entry points.)</p><p>📦 To see the data associated with a specific key, use the get command: get persons-by-id::1 , this will print out the serialized data for that cache entry. Voilà! You’re seeing Redis in action 🧠⚡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhHlRYFch7XI0ukui92p1w.png" /><figcaption>information of application cache inside Redis container</figcaption></figure><p>✅ Doing this, we can see that Redis is indeed being used to <strong>improve the performance</strong> of our application.</p><p>🆕 Now, let’s call the <strong>create new Person</strong> endpoint to test our @CacheEvict annotation, which invalidates the &quot;persons-all&quot; cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*5TX_RJtFIcXfHUE6Togcbg.png" /><figcaption>create endpoint that triggers cache evict of listAll</figcaption></figure><p>🔄 After making that call, let’s check the Redis container again to see if the cache was properly deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*wBujP7ImQnuInZgs7o1pTw.png" /><figcaption>execution after cache evict triggered by create endpoint</figcaption></figure><p>🗑️ The cache has been deleted, as we can see. Now, let’s call the <strong>getAll</strong> endpoint again and check how long it takes to return the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*K2CUHrlhEkLceJTqVQIDPg.png" /><figcaption>new list with newly added person, cache invalidated</figcaption></figure><p>💾 After that new <strong>getAll</strong> endpoint call, a fresh cache entry is added to Redis with the updated list.</p><p>✅ Now we have a fully configured Redis server adding cache to our application and boosting its performance.</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography</h3><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/redis-cache">Java-Series/redis-cache at master · AugustoKlaic/Java-Series</a></p><p><a href="https://medium.com/@susantamon/top-5-java-caching-frameworks-for-spring-boot-integration-05557844aa2e">Top 5 Java Caching Frameworks for Spring Boot Integration | by Susanta Mondal | Medium</a></p><p><a href="https://redis.io/">Redis — The Real-time Data Platform</a></p><p><a href="https://www.youtube.com/watch?v=YcI9b-lgi7w">(21) Aprenda a usar cache nos seus projetos Spring Boot! — YouTube</a></p><p><a href="https://hub.docker.com/_/redis">redis — Official Image | Docker Hub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b35d9507b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Database change management]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-database-change-management-79bef11b96d2?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/79bef11b96d2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database-management]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[liquibase]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 02:29:03 GMT</pubDate>
            <atom:updated>2025-06-03T02:29:03.184Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Liquibase</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Yrc0VxjeibnzsJeQ.png" /></figure><p>Let’s talk about a cool feature to add to a Java application, especially when working on big projects with relational databases. Today’s topic is about <strong>Liquibase</strong>, a tool that helps keep the database on the same page across every developer’s machine or environment. ⚙️</p><p>Liquibase is a database change management tool that helps organize and maintain all change scripts, from the beginning to the end of a project. It’s like applying the concept of DevOps to a relational database, turning it into a continuous integration of changes. 🚀</p><p>To give a more concrete example: at the beginning of a project, a team designs the database schema with its tables and relationships (FKs, PKs). But during development, it becomes necessary to add 20 more tables, redo all the column types of a table, change various table relationships… and all of this happens over several weeks. The result? A lot of change scripts added to the project to keep the database up to date.</p><p>Given that context, imagine a messy project where people don’t keep any documentation, the project structure is bad, and scripts are just saved in a folder without any order or guarantee that they’ve been executed. Then a new dev arrives on the project and starts setting up their environment. They’ll have to execute all the scripts one by one, in the correct order, to get the database aligned with production. That’s a tough task, will consume a lot of time, and introduces a dozen potential failure points. 😵‍💫</p><p>To solve that problem, people started using database migration tools. Their responsibility is to keep track of all the scripts that have been executed on a database. So when someone needs to recreate everything from scratch (like in our new hire scenario above), the tool will execute every script from the first one to the last, delivering the same database in every environment. ✅</p><p>To achieve this, some tools use an “admin” table in the database. This table has columns like id, script_name, execution_date, user, hashes… and every script executed inserts a row into that table. All the changes are now properly registered.</p><p>There are a lot of benefits to having this type of tool in a project:</p><ul><li><strong>Visibility</strong>: everyone can see the latest changes applied to the database. 👀</li><li><strong>Collaboration</strong>: everyone can work in separate environments with an up-to-date schema. 🤝</li><li><strong>Easier maintenance</strong>: rollbacks are easier to apply, and new changes are documented.</li><li><strong>Standardization</strong>: everyone follows a process to change something in the database, starting with the script file name.</li></ul><p>Liquibase is one of many tools on the market, like Flyway, SQLDiff, Fluent… all these tools have a similar behavior and objective: to facilitate and organize changes in relational databases, creating an execution hierarchy for the scripts. So, every time the project starts, all changes are applied in order — or it just applies the changes that haven’t been executed yet.</p><p>In this text, I’ll focus on <strong>Liquibase</strong>. So… let’s get to the code! 💻</p><p>To start, we’ll need a sample Java project, a Docker container running any relational database (I chose <strong>PostgreSQL</strong>), and a sample database to be manipulated. The project will be available on my <strong>GitHub</strong> page. 📦</p><p>The Docker part is very straightforward: just get the official image for PostgreSQL. It should look something like this:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  database:<br>    image: postgres:latest<br>    container_name: postgres<br>    environment:<br>      POSTGRES_USER: myuser<br>      POSTGRES_PASSWORD: mypassword<br>      POSTGRES_DB: liquibase-test<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - db_data:/var/lib/postgresql/data<br>volumes:<br>  db_data:</pre><p>This <strong>Docker Compose</strong> script is pretty simple: we’re pulling the latest official image of <strong>PostgreSQL</strong>, giving a name to the container, setting up some environment variables to configure our database, exposing the standard port, and setting up a volume to persist the data. 🐳</p><p>All explained! Now, open a terminal in the directory where the postgres-server-docker.yml (or whatever name you chose) is located and run the command:</p><pre>docker compose -p postgres-server -f postgres-server-docker.yml up -d</pre><p>This command will build the image, start the container, and assign the Docker project name postgres-server. 🐘</p><p>Liquibase will be managed by our <strong>Spring Boot</strong> project, so to test and use it, we’ll need to set up some dependencies in the build.gradle script.</p><p>The following script is what I used to run the project:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.5.0&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.liquibase&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(17)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br><br>    implementation &#39;org.liquibase:liquibase-core&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-data-jpa&#39;<br>    implementation &#39;org.postgresql:postgresql&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    compileOnly &#39;org.projectlombok:lombok&#39;<br>    annotationProcessor &#39;org.projectlombok:lombok&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p>This <strong>Gradle</strong> build script will add all the dependencies needed to create a simple endpoint, map a basic entity from the database using <strong>JPA</strong>, add <strong>Lombok</strong> annotations to make coding easier, and of course, include the <strong>Liquibase</strong> dependency. 🛠️</p><p>After building the project, let’s add some simple Java classes for testing purposes — something like this:</p><pre>@RestController<br>@RequestMapping(&quot;/person&quot;)<br>@RequiredArgsConstructor<br>public class PersonController {<br><br>    private final PersonRepository repository;<br><br>    @GetMapping(&quot;&quot;)<br>    public List&lt;Person&gt; getPersons() {<br>        return repository.findAll();<br>    }<br>}<br><br>@Repository<br>public interface PersonRepository extends JpaRepository&lt;Person, Long&gt; {<br>}<br><br>@Entity<br>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Table(name = &quot;person&quot;)<br>public class Person {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    @Column(name = &quot;name&quot;)<br>    private String name;<br><br>    @Column(name = &quot;last_name&quot;)<br>    private String lastName;<br><br>    @Column(name = &quot;age&quot;)<br>    private Integer age;<br><br>    @Column(name = &quot;email&quot;)<br>    private String email;<br>}<br></pre><p>This is just an entity mapping class and an endpoint to list results. I’ve merged three classes in the code snippet above, so when creating it yourself, make sure to separate each of them. 😉</p><p>After adding those classes, we need to configure the database, <strong>Liquibase</strong>, and the connections. To do that, we’ll use the application.properties file from <strong>Spring</strong>. It should look like this:</p><pre>spring.application.name=liquibase<br><br>spring.datasource.driver-class-name=org.postgresql.Driver<br>spring.datasource.url=jdbc:postgresql://localhost:5432/liquibase-test<br>spring.datasource.username=myuser<br>spring.datasource.password=mypassword<br>spring.jpa.hibernate.ddl-auto=none<br>spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.yaml</pre><p>That configuration sets the database driver for <strong>PostgreSQL</strong> that we imported in the build.gradle script, adds the URL connection string so our application can find the database, and sets the username and password for connecting to the database (⚠️ don’t do that in a production environment).</p><p>The property ddl-auto set to none tells the <strong>JPA</strong> framework not to make any changes in the database — that’s <strong>Liquibase</strong>&#39;s job.</p><p>The last property tells <strong>Liquibase</strong> where the master changelog file is located.</p><p>So now, we’re all set with configurations and code! Let’s move on to the <strong>Liquibase</strong> scripts.</p><p>Liquibase can work with different types of configurations: it can run <strong>YAML</strong> or <strong>XML</strong> scripts. In these scripts, you can either specify database commands directly using <strong>Liquibase’s declarative language</strong>, or point to <strong>SQL</strong> files with the commands you want.</p><p>Personally, I think it’s better to use <strong>SQL</strong> scripts for better organization, understanding, debugging, and to keep the changelog files smaller. 🗂️</p><p>In this project, we’ll be using a master changelog in <strong>YAML</strong> format and <strong>SQL</strong> scripts. The master changelog file must be located in the resources folder of the application, inside another folder called /resources/db/changelog.</p><p>After creating the folder, you need to create a file named: db.changelog-master.yaml. In this file, we’ll reference all our SQL scripts so <strong>Liquibase</strong> can execute them.</p><p>So the changelog file will look like this:</p><pre>databaseChangeLog:<br>  - changeSet:<br>      id: 1<br>      author: augusto<br>      changes:<br>        - sqlFile:<br>            path: scripts/202505301120_create-table-person.sql<br>            relativeToChangelogFile: true<br>            encoding: utf8<br>  - changeSet:<br>      id: 2<br>      author: augusto<br>      changes:<br>        - sqlFile:<br>            path: scripts/202505301130_insert-person.sql<br>            relativeToChangelogFile: true<br>            encoding: utf8<br>  - changeSet:<br>      id: 3<br>      author: augusto<br>      changes:<br>        - sqlFile:<br>            path: scripts/202505301140_alter-table-add-email-column.sql<br>            relativeToChangelogFile: true<br>            encoding: utf8<br>  - changeSet:<br>      id: 4<br>      author: augusto<br>      changes:<br>        - sqlFile:<br>            path: scripts/202505301150_insert-person-with-email.sql<br>            relativeToChangelogFile: true<br>            encoding: utf8</pre><p>The changelog file will run <strong>4 SQL scripts</strong> with a variety of commands. In my example here, I’m creating a table, adding a row to it, then modifying the table and inserting another row.</p><p>Under the db/changelog folder, you can create any subdivisions you want to better organize your SQL scripts. I chose to create just a subfolder called scripts to store all my SQL files, as you can see in the paths of the SQL files above. 🗂️</p><p>The command relativeToChangelogFile tells <strong>Liquibase</strong> that the files are located in a folder relative to the changelog, so we don’t need to write the full file path.</p><p>The id and author fields are for <strong>audit purposes</strong> and organization.</p><p>Here are the <strong>SQL files</strong> I used:</p><pre>--File 1<br>CREATE TABLE person(<br>    id        BIGINT PRIMARY KEY,<br>    name      TEXT NOT NULL,<br>    last_name TEXT,<br>    age       BIGINT<br>);<br><br>-- File 2<br>insert into person (id, name, last_name, age)<br>values(1, &#39;robertin&#39;, &#39;tralalero&#39;, 30);<br><br>--File 3<br>alter table person add column email TEXT;<br><br>update person<br>set email = &#39;robertin@email.com&#39;<br>where email is null;<br><br>alter table person alter column email set NOT NULL;<br><br>--File 4<br>insert into person (id, name, last_name, age, email)<br>values(2, &#39;augusto&#39;, &#39;tralala&#39;, 28, &#39;augusto@email.com&#39;);</pre><p>To execute and test everything, you just need to run the <strong>Spring Boot</strong> app. It will run <strong>Liquibase</strong>, create the table, and insert the sample data. After the application is fully started, you can call the /person endpoint to see the data that Liquibase inserted into the table.</p><p>And that is it for this tutorial. Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography:</h3><p><a href="https://medium.com/@KeivanDamirchi/database-change-management-946af9c02169">Database Change Management</a></p><p><a href="https://www.liquibase.com/">https://www.liquibase.com/</a></p><p><a href="https://medium.com/@cat.edelveis/using-liquibase-with-spring-boot-tutorial-79245a0b79a6">https://medium.com/@cat.edelveis/using-liquibase-with-spring-boot-tutorial-79245a0b79a6</a></p><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/liquibase">https://github.com/AugustoKlaic/Java-Series/tree/master/liquibase</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79bef11b96d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Observability]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-observability-9e04ef7b5be6?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e04ef7b5be6</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[elk-stack]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 03:08:18 GMT</pubDate>
            <atom:updated>2025-04-25T03:08:18.801Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>ELK stack — elasticsearch, logstash, and kibana</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GjyRGXb4PkSJlK4W.png" /></figure><p>So let’s talk about the <strong>ELK Stack</strong> 🔍. This stack is a widely used tool for observability across systems. These guys are like the <em>three musketeers</em> — always working together with one mission: helping developers understand what’s happening inside the application in real-time, in a simple way, without needing to SSH into the server to grab the log file manually.</p><p>Observability has become a <strong>hot topic</strong> nowadays, especially due to the growing adoption of <strong>cloud-native systems</strong> across companies. And that’s a good thing! It encourages applications to produce more meaningful logs — logs that tell you <em>what’s going on</em>, <em>where the data is flowing</em>, or <em>where exactly an error occurred</em>. All of this becomes crucial when dealing with production incidents or even those annoying little bugs 🐞.</p><p>The best practice here is to write <strong>relevant and purposeful logs</strong> — logs that actually help during troubleshooting. Avoid flooding your application with lines like &quot;passed here&quot; or &quot;went through here&quot;. This kind of log noise just burdens the logging infrastructure, increasing storage and processing costs unnecessarily.</p><p>It’s also important to highlight that observability is based on <strong>three key pillars</strong>: <strong>logs</strong>, <strong>metrics</strong>, and <strong>traces</strong>. The ELK Stack handles all of them very well 💪. It allows you to create dashboards for visualizing metrics, set alerts based on traces and collected data, and centralize everything into a single place. This makes it easier to detect and resolve issues — and even gain useful insights from the data.</p><p>👉 In this article, I’ll walk you through how to <strong>set up the ELK Stack using Docker</strong>, and how to <strong>connect logs generated by a Java application</strong> so you can visualize them directly in <strong>Kibana</strong>.</p><p>So, how does the ELK Stack work?</p><p>The stack — just as the name suggests — is a <strong>combination of three technologies</strong>, each with a unique responsibility. The acronym stands for:</p><ul><li><strong>Elasticsearch</strong></li><li><strong>Logstash</strong></li><li><strong>Kibana</strong></li></ul><p>Each of them plays a <strong>crucial role</strong> in the stack’s ecosystem. 🧩</p><p>The process starts with <strong>Logstash</strong> ⚙️. Logstash is a <strong>pipeline-based tool</strong> that performs actions on top of the incoming data — in this case, log data. In its configuration script, you define <strong>the input source</strong> (like a file, TCP, terminal, etc.), <strong>the filters</strong> to apply to the log stream, and finally <strong>the output</strong>, which determines where the processed logs will be sent.</p><p>Logstash can send log data to various destinations like <strong>Kafka</strong>, among others. However, in most cases, Logstash sends its data to <strong>Elasticsearch</strong>. Why? Because it’s part of the same stack — they’re designed to work together seamlessly. And more importantly, Elasticsearch’s role is to <strong>store and index</strong> log data efficiently.</p><p>Elasticsearch is a <strong>high-performance search engine</strong>, focused on indexing and retrieving structured data in real-time. It’s a <strong>document-oriented database</strong>, similar to MongoDB, and all communication with it happens via <strong>RESTful APIs</strong>.</p><p>Once Elasticsearch has stored the data, it’s time for <strong>Kibana</strong> 📊 to shine. Kibana is the visualization layer — it allows you to <strong>query, filter, and visualize</strong> log data using customizable <strong>dashboards</strong>. You can filter logs by <strong>timestamp, application name, keywords, error types</strong>, and much more. It’s possible to build complete dashboards to monitor <strong>errors, memory usage, or log volume per application</strong>, for example.</p><p>Kibana is a very powerful tool. So, if you’re looking for <strong>better observability</strong> in a <strong>scalable and distributed way</strong>, the <strong>ELK Stack</strong> is definitely a solid choice.</p><p>👉 Now let’s move on to the good part: <strong>the code</strong>…</p><p>Now let’s build a <strong>Java application</strong> that produces logs to be visualized in <strong>Kibana</strong>. It will be a simple app using <strong>SLF4J</strong> as the logging facade. We’ll write logs in the <strong>controller</strong>, <strong>service</strong>, and <strong>repository</strong> layers. The controller will act as the <strong>entry point</strong> to trigger the logging process — just like it works in many real-world APIs across different companies.</p><p>Before diving into the code, we need to have the <strong>ELK Stack up and running</strong>. For that, I’ll use the following docker-compose setup: 🐳👇</p><pre>version: &#39;3&#39;<br>services:<br>  elasticsearch:<br>    image: elasticsearch:8.17.2<br>    container_name: elasticsearch<br>    volumes:<br>      - elastic_data:/usr/share/elasticsearch/data/<br>    environment:<br>      ES_JAVA_OPTS: &quot;-Xmx256m -Xms256m&quot;<br>      discovery.type: single-node<br>      xpack.security.enabled: false<br>      bootstrap.memory_lock: true<br>    ulimits:<br>      memlock:<br>        soft: -1<br>        hard: -1<br>    ports:<br>      - &#39;9200:9200&#39;<br>      - &#39;9300:9300&#39;<br>    networks:<br>      - elk<br>  logstash:<br>    image: logstash:8.17.2<br>    container_name: logstash<br>    volumes:<br>      - ./config-logstash:/usr/share/logstash/pipeline<br>    depends_on:<br>      - elasticsearch<br>    ports:<br>      - &#39;9600:9600&#39;<br>      - &#39;5000:5000&#39;<br>      - &#39;5044:5044&#39;<br>    environment:<br>      LS_JAVA_OPTS: &quot;-Xmx256m -Xms256m&quot;<br>    networks:<br>      - elk<br>  kibana:<br>    image: kibana:8.17.2<br>    container_name: kibana<br>    ports:<br>      - &#39;5601:5601&#39;<br>    environment:<br>      - ELASTICSEARCH_URL=http://elasticsearch:9200<br>    depends_on:<br>      - elasticsearch<br>    networks:<br>      - elk<br>networks:<br>  elk:<br>    driver: bridge<br><br>volumes:<br>  elastic_data:<br>    driver: local</pre><p>This docker-compose file sets up the three services that make up the <strong>ELK Stack</strong>: <strong>Elasticsearch</strong>, <strong>Logstash</strong>, and <strong>Kibana</strong>. All of them communicate within the same custom Docker network called &quot;elk&quot; (defined at the end of the file), and Elasticsearch will persist data using a volume.</p><h3>🔍 Elasticsearch Service</h3><p>We’re using the official Elasticsearch Docker image. The service is given a name, and a <strong>persistent volume</strong> is mounted to ensure that log data isn’t lost after shutdowns or restarts.</p><p>In the environment section:</p><ul><li>ES_JAVA_OPTS sets both the <strong>minimum and maximum heap size</strong>, preventing Elasticsearch from consuming too much memory.</li><li>discovery.type=single-node tells Elasticsearch to run in <strong>standalone mode</strong>, not as part of a cluster.</li><li>xpack.security.enabled=false disables authentication (useful for local dev).</li><li>bootstrap.memory_lock=true prevents the OS from swapping the container’s memory, improving performance.</li></ul><p>Also, we use ulimits to support memory locking, map the necessary ports, and assign the container to the shared elk network.</p><h3>🔄 Logstash Service</h3><p>Here we use the official Logstash image and assign a name to the container.</p><p>In the volumes section, we <strong>mount a local folder</strong> from the host to the container so we can pass our custom configuration file (e.g. logstash.conf).</p><p>The depends_on directive ensures that <strong>Logstash starts only after Elasticsearch</strong> is up and running.</p><p>We also configure:</p><ul><li>LS_JAVA_OPTS to control Java heap memory (just like we did with Elasticsearch).</li><li>The ports:</li><li>9600: for Logstash&#39;s <strong>monitoring API</strong>.</li><li>5000: to <strong>receive logs via TCP/UDP in JSON format</strong>.</li><li>5044: to <strong>receive logs via Filebeat</strong>.</li></ul><p>And of course, the container joins the elk network.</p><h3>📊 Kibana Service</h3><p>We’re using the official Kibana image and setting its container name.</p><p>In the environment section:</p><ul><li>ELASTICSEARCH_URL is required to connect Kibana to the Elasticsearch service.</li></ul><p>We expose the web interface by mapping port 5601, add the container to the shared network, and use depends_on to ensure <strong>Kibana starts after Elasticsearch</strong>.</p><h3>🛠 Before We Start the ELK Server…</h3><p>We need to create a <strong>Logstash pipeline configuration file</strong>, which defines <strong>how Logstash should process incoming logs</strong> on startup. As mentioned earlier, this configuration is required so Logstash knows where logs come from, how to transform them, and where to send them. In the docker-compose file at the logstash , we mapped a local folder like this:</p><pre>volumes:<br>  - ./config-logstash:/usr/share/logstash/pipeline</pre><p>This means that we should place our pipeline configuration file (named logstash.conf) inside a folder called config-logstash in the host machine. When the container starts, it will load this configuration automatically.</p><p>Here’s an example of what that file looks like: 👇</p><pre>input {<br>  tcp {<br>    port =&gt; 5000<br>    codec =&gt; json_lines<br>  }<br>}<br><br>filter {<br>  json {<br>    source =&gt; &quot;message&quot;<br>  }<br>}<br><br>output {<br>  stdout { codec =&gt; rubydebug }<br><br>  elasticsearch {<br>    hosts =&gt; [&quot;http://elasticsearch:9200&quot;]<br>    index =&gt; &quot;spring-logs-%{+YYYY.MM.dd}&quot;<br>  }<br>}</pre><p>The logstash.conf file follows a basic structure made of three main sections:</p><h3>🔌 input block</h3><p>This section defines <strong>where the logs are coming from</strong> and in which format.<br> In our case:</p><ul><li>Logs are received via <strong>TCP</strong> on <strong>port 5000</strong>.</li><li>The expected data format is <strong>JSON</strong>.</li></ul><h3>🧰 filter block</h3><p>This block is optional, but it’s used to <strong>transform or enrich the logs</strong>.<br> For example, you could:</p><ul><li>Add tags or fields.</li><li>Parse dates or strings.</li><li>Remove unnecessary fields.</li></ul><p>In our case we are just telling logstash to treat the content of the field message as JSON value.</p><h3>🚀 output block</h3><p>Here we define <strong>where Logstash should send the logs</strong>. In this case:</p><ul><li>Logs go to <strong>Elasticsearch</strong>.</li><li>We define the hosts and optionally the index name.</li></ul><h3>✅ Running the ELK Stack</h3><p>Once everything is configured, open a terminal in the directory where the elk-stack-docker.yml (or whatever name you chose) is located and run the command:</p><pre>docker compose -p elk-stack-server -f elk-stack-docker.yml up -d</pre><p>This command:</p><ul><li>Builds all necessary images.</li><li>Starts the <strong>Elasticsearch</strong>, <strong>Logstash</strong>, and <strong>Kibana</strong> containers in detached mode.</li><li>Assigns the Docker project name elk-stack-server.</li></ul><h3>📦 Java Application</h3><p>Now that your ELK stack is up and running, we move on to the Java app.</p><p>The structure is simple:<br> A classic layered architecture with:</p><ul><li>A <strong>Controller</strong> — acts as the entry point.</li><li>A <strong>Service</strong> — contains the business logic.</li><li>A <strong>Repository</strong> — simulates data access or external communication.</li></ul><p>Each layer writes logs using the <strong>Slf4j</strong> logger. This helps track <strong>where each log comes from</strong> (controller, service, or repository), just like you’d expect in real-world applications.</p><p>Here’s a simplified example of the application structure: 👇</p><pre>@RestController<br>@RequestMapping(&quot;/log&quot;)<br>public class ControllerToLog {<br>    private static final Logger logger = LoggerFactory.getLogger(ControllerToLog.class);<br>    private final ServiceToLog service;<br><br>    public ControllerToLog(ServiceToLog service) {<br>        this.service = service;<br>    }<br><br>    @GetMapping<br>    public ResponseEntity&lt;Void&gt; startLogging() {<br>        logger.info(&quot;Log from: {}&quot;, this);<br>        service.logSomething();<br>        return ResponseEntity.noContent().build();<br>    }<br>}<br><br>@Service<br>public class ServiceToLog {<br>    private static final Logger logger = LoggerFactory.getLogger(ServiceToLog.class);<br>    private final RepositoryToLog repository;<br><br>    public ServiceToLog(RepositoryToLog repository) {<br>        this.repository = repository;<br>    }<br><br>    public void logSomething() {<br>        for (int i = 0; i &lt; 10; i++) {<br>            logger.info(&quot;Log number: {} from service {}&quot;, i, this);<br>        }<br>        repository.logRepository();<br>    }<br>}<br><br>@Repository<br>public class RepositoryToLog {<br>    private static final Logger logger = LoggerFactory.getLogger(RepositoryToLog.class);<br><br>    public void logRepository() {<br>        logger.info(&quot;Log from repository: {}&quot;, this);<br>    }<br>}</pre><p>Now that we have our ELK server up and running, and the application ready to generate logs that will be monitored in Kibana, we still need <strong>one last configuration</strong> in our application: a way to actually send those logs to Logstash via a TCP connection.</p><p>To do this, we’ll create a file named logback-spring.xml. This file will tell our Spring Boot application <strong>how to send logs to Logstash</strong> — whether it’s through Filebeat, a direct TCP/UDP connection, etc. It will also define <strong>which log levels</strong> (e.g., INFO, DEBUG, ERROR) should be sent.</p><p>This file must be placed in the src/main/resources directory so that Spring can find and apply the logging configuration properly at startup.</p><p>📄 Below is an example structure of the logback-spring.xml file:</p><pre>&lt;configuration&gt;<br>    &lt;include resource=&quot;org/springframework/boot/logging/logback/base.xml&quot;/&gt;<br><br>    &lt;appender name=&quot;LOGSTASH&quot; class=&quot;net.logstash.logback.appender.LogstashTcpSocketAppender&quot;&gt;<br>        &lt;destination&gt;localhost:5000&lt;/destination&gt;<br>        &lt;encoder class=&quot;net.logstash.logback.encoder.LogstashEncoder&quot;/&gt;<br>    &lt;/appender&gt;<br><br>    &lt;logger name=&quot;org.springframework&quot; level=&quot;INFO&quot;/&gt;<br><br>    &lt;root level=&quot;INFO&quot;&gt;<br>        &lt;appender-ref ref=&quot;LOGSTASH&quot;/&gt;<br>    &lt;/root&gt;<br>&lt;/configuration&gt;</pre><p>This XML file contains several important tags.</p><p>The &lt;include&gt; tag simply brings in the default logback configuration provided by Spring Boot.</p><p>The &lt;appender&gt; tag defines <strong>how</strong> Spring will send logs. In this case, we&#39;re using LogstashTcpSocketAppender.<br>Inside the appender block, we have two key tags:</p><ul><li>&lt;destination&gt;: defines the address and port where Spring Boot will send logs — in our case, directly to Logstash over TCP.</li><li>&lt;encoder&gt;: uses a standard configuration to format logs as JSON, making them compatible with Elasticsearch.</li></ul><p>After the appender block, we define logging behavior with:</p><ul><li>&lt;logger&gt;: this sets the log level for the Spring Framework itself to INFO.</li><li>&lt;root&gt; along with &lt;appender-ref&gt;: this defines the log level for the entire application (INFO and above), and links it to the Logstash appender so everything gets sent to Logstash.</li></ul><p>✅ At this point, our application is fully configured and ready to send logs to the ELK stack.</p><p>To test it:</p><ol><li>Start the Java application.</li><li>Make a request to the exposed endpoint: /log.</li></ol><p>This should trigger some log events that will be picked up by Logstash and saved into Elasticsearch.</p><p>Now let’s <strong>open Kibana</strong> to check if everything is working.</p><p>In the docker-compose.yml file, under the Kibana service, we mapped a port to expose Kibana’s web interface to the host machine. So just open your browser and go to: <a href="http://localhost:5601/">http://localhost:5601/</a>. You should land on Kibana’s home page.</p><p>To view the logs, go to the <strong>“Discover”</strong> tab — it’s located on the left-hand menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*YD9DixQoftPVNejpVKWu5w.png" /><figcaption>side menu</figcaption></figure><p>When you click on the <strong>Discover</strong> menu, Kibana takes you to the section where your logs will be displayed. But… where are the logs? Well, <strong>logs only show up if there’s a Data View configured</strong>. A <strong>Data View</strong> in Kibana is basically a way to tell Kibana:</p><blockquote><em>“Hey, look into this index pattern in Elasticsearch to fetch data.”</em></blockquote><p>If there’s no data view set up, Kibana won’t know which logs to show. To fix that, you need to create a Data View — and you can do that in two ways:</p><ul><li><strong>Using the Kibana UI</strong> (recommended for most cases),</li><li>Or using <strong>Kibana’s REST API</strong> if you prefer automating the process.</li></ul><p>Using the <strong>UI</strong>, after clicking the <strong>Create Data View</strong> button, you will be redirected to a window where you can configure the Data View. In this window, you’ll be able to see the index created by the Logstash pipeline (as defined earlier in the logstash.conf file).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzTfX9VPkzGs56Jk1F7dcw.png" /><figcaption>UI create data view</figcaption></figure><p>Every log generated by your application will be stored in this index, but the <strong>index name will change daily</strong>, as I used a wildcard to dynamically add the current date to the index in the Logstash pipeline. So, if your app is sending logs correctly to Elasticsearch, the index will be automatically created each day.</p><p>Now, you need to:</p><ol><li><strong>Define a name</strong> for the data view (choose something meaningful so you know which service is sending the logs),</li><li><strong>Set an index pattern</strong>: This pattern acts as a filter that tells Kibana which Elasticsearch indexes to use when displaying data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xz0SKB0CiUMZ3jMtnX_shA.png" /></figure><p>Alternatively, using <strong>Kibana’s REST API</strong>, you can easily create a Data View by making the following request:</p><pre>curl --location &#39;http://localhost:5601/api/data_views/data_view&#39; \<br>--header &#39;kbn-xsrf: true&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br>    &quot;data_view&quot;: {<br>      &quot;title&quot;: &quot;spring-logs-*&quot;,<br>      &quot;name&quot;: &quot;spring-logs&quot;,<br>      &quot;timeFieldName&quot;: &quot;@timestamp&quot;<br>    }<br>  }&#39;</pre><p>After creating the Data View, simply <strong>refresh the page</strong>, and the logs will appear in the <strong>Discovery</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AoKv7LTinPZ2vukSD_mhg.png" /><figcaption>logs on discovery tab</figcaption></figure><p>Now, we have configured a fully functional ELK server to add observability to our application.</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h3>Bibliography</h3><p><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/elk-basics">Java-Series/elk-basics at master · AugustoKlaic/Java-Series · GitHu</a>b</p><p><a href="https://www.elastic.co/elastic-stack">Elastic Stack: (ELK) Elasticsearch, Kibana &amp; Logstash | Elastic</a></p><p><a href="https://www.elastic.co/blog/getting-started-with-the-elastic-stack-and-docker-compose">Getting started with the Elastic Stack and Docker-Compose | Elastic Blog</a></p><p><a href="https://medium.com/@marouanetester/deploying-elk-stack-using-docker-compose-6fd0978a3b0a">Deploying ELK stack using Docker-Compose | by Marouane Louguid | Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e04ef7b5be6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java series: Behavior Testing]]></title>
            <link>https://medium.com/@augusto.klaic/java-series-behavior-testing-9ffc19d7bd2c?source=rss-6b3cdb3a1f05------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ffc19d7bd2c</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[bdd-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[cucumber]]></category>
            <dc:creator><![CDATA[Augusto Sopelsa Klaic]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 03:49:30 GMT</pubDate>
            <atom:updated>2025-02-19T03:49:30.978Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Cucumber</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*sDutmuo4o2YnolenJWzqkQ.jpeg" /></figure><p>Today, let’s talk about a topic I’m not very familiar with. I know what Cucumber is and what it’s useful for, but I’ve never actually used it in my work career until now. So, let’s explore this topic together.</p><p>Cucumber is a way to bridge the gap between the development and business areas — almost like a readable unit test that a Product Owner (P.O.) can understand, showing what will happen and what the test outcome will be. But why is that a good thing? Because bringing the technical team closer to the business team is beneficial for software development. The tech team becomes more engaged in the process itself, needing to talk with business people to understand the nuances and rules of the business process. This reduces time spent in meetings discussing these details and increases the time spent developing valuable code.</p><p>It also creates living documentation of the software, helping new hires understand the codebase. Additionally, it may reveal knowledge gaps in some business processes, even for experienced developers, helping them solve bugs or handle edge cases.</p><p>BDD — Behavior-Driven Development — is usually based on a user story that defines what a piece of software should do and how it should behave under certain conditions. This is the core of Cucumber: given a scenario, when something happens, then an expected outcome occurs.</p><p>Cucumber supports BDD by allowing test scenarios to be written in plain text, so even non-developers can read and understand the system’s behavior. This way, behavior tests become the system’s specification, making it accessible to everyone. For example:</p><pre>Feature: Addition is calculated between two numbers<br>  <br>  Scenario: Two numbers addition<br>    Given operator is 3.0 and operand is 2.0 and operation is &quot;ADDITION&quot;<br>    When calculation is performed<br>    Then result must be 5.0</pre><p>Cucumber works by interpreting specific syntax rules called Gherkin. The example above shows a simple structure of the syntax Gherkin uses. A test case must follow this setup:</p><ul><li><strong>Feature</strong>: This is the name of the test and should be similar to the file name where it is written.</li><li><strong>Scenario</strong>: This represents a concrete example, describing how the software should behave.</li><li><strong>Given, When, Then</strong>: These are the steps of the test. Cucumber will execute this part.</li></ul><p>The second line is ignored by Cucumber and serves only as documentation.</p><p>Cucumber transforms plain text into a structured set of rules that it can understand and links the written test case to a corresponding Java unit test. This is where the actual code logic is implemented:</p><pre>@Given(&quot;operator is {double} and operand is {double} and operation is {string}&quot;)<br>public void givenOperatorAndOperand(Number operator, Number operand, String operation) {<br>  request = new CalculationRequest(operator, operand, operation);<br>}<br><br>@When(&quot;calculation is performed&quot;)<br>public void whenOperatorIsAddedWithOperand() {<br>  result = service.doCalculation(request);<br>}<br><br>@Then(&quot;result must be {double}&quot;)<br>public void thenResultMustBe(Number result) {<br>  assertEquals(result, this.result.getResult());<br>}</pre><p>In a simplified way, Cucumber translates the plain-text scenario into the corresponding Java code, matching the keywords <strong>Given</strong>, <strong>When</strong>, and <strong>Then</strong>, executing them one after another until the final result is checked.</p><p>Another cool feature is that you can inject variable values directly from the plain-text definition. This is really useful for result validation because the business team can define all the operation values and already know the expected outcome.</p><p>Another important point is that Cucumber allows multiple .feature files to be bound to a single .java behavior test. This makes it easier to reuse the same @Given, @When, or @Then declarations across similar tests, avoiding code repetition just to increase test coverage (following the <strong>DRY</strong> principle).</p><p>When exceptional cases occur in tests, such as an exception or an unexpected result, Cucumber allows multiple possible outcomes for the same step. For example, if an exception might occur in the @Then step, you can define two or more @Then steps by simply changing the matching phrase in the annotation and in the plain-text file (see the example below).</p><p>Now, let’s get to the coding part! In this tutorial, I used a simple Java app that performs basic math operations, just to create some Cucumber test cases.</p><p>I ran into an issue where my configuration for running tests using IntelliJ IDE and Spring always threw a context error. I couldn’t find a way to solve it, so I decided to run the tests using a Gradle task instead.</p><p>Here are all the steps:</p><p>build.gradle</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.4.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.7&#39;<br>}<br><br>group = &#39;com.augusto.bdd-basics&#39;<br>version = &#39;0.0.1&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br><br>    implementation &#39;io.cucumber:cucumber-java:7.21.1&#39;<br>    implementation &#39;io.cucumber:cucumber-spring:7.21.1&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}<br><br>configurations {<br>    cucumberRuntime {<br>        extendsFrom testImplementation<br>    }<br>}<br><br>task cucumberCli() {<br>    dependsOn assemble, testClasses<br>    doLast {<br>        javaexec {<br>            main = &quot;io.cucumber.core.cli.Main&quot;<br>            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output<br>            args = [<br>                    &#39;--plugin&#39;, &#39;pretty&#39;,<br>                    &#39;--plugin&#39;, &#39;html:target/cucumber-report.html&#39;,<br>                    &#39;--glue&#39;, &#39;com.augusto.bddbasics&#39;,<br>                    &#39;src/test/resources&#39;]<br>        }<br>    }<br>}</pre><p>I added this Gradle task command in the build.gradle file to run the Cucumber tests using the command: gradle cucumberCli . In this file, there are some important points to highlight:</p><ul><li><strong>Dependencies</strong>: cucumber-java: Needed to write tests using Cucumber and Java. cucumber-spring: Required to use Spring annotations in Cucumber tests, like @Autowired.</li><li><strong>Configuration — </strong><strong>cucumberRuntime</strong>: Allows Cucumber to run independently from JUnit’s test task. Loads all dependencies from testImplementation.</li><li><strong>Task — </strong><strong>cucumberCli</strong>: Allows Cucumber tests to be run directly from the command line. Ensures the code is compiled before running the tests (dependsOn assemble, testClasses). Uses javaexec to call Cucumber&#39;s main execution engine. --plugin pretty: Displays test output in the terminal in a readable format. --plugin html:target/cucumber-report.html: Generates an HTML report of the tests and saves it in target/cucumber-report.html. --glue com.augusto.bddbasics: Defines the base package where the step definition files (@Given, @When, @Then) are located. &#39;src/test/resources&#39;: Specifies the path where the .feature files of Cucumber are located.</li></ul><p>TestContextLoader.java</p><pre>@SpringBootTest<br>@CucumberContextConfiguration<br>public class TestContextLoader {<br>}</pre><p>This file is needed to load the spring context when running the tests and auto configure the cucumber.</p><p>CalculationBehaviorTest.java</p><pre>public class CalculationBehaviorTest {<br><br>    private CalculationRequest request;<br>    private CalculationResponse result;<br>    private Exception exception;<br><br>    @Autowired<br>    private CalculationService service;<br><br>    @Given(&quot;operator is {double} and operand is {double} and operation is {string}&quot;)<br>    public void givenOperatorAndOperand(Number operator, Number operand, String operation) {<br>        request = new CalculationRequest(operator, operand, operation);<br>        exception = null;<br>    }<br><br>    @When(&quot;calculation is performed&quot;)<br>    public void whenOperatorIsAddedWithOperand() {<br>        try {<br>            result = service.doCalculation(request);<br>        } catch (Exception e) {<br>            exception = e;<br>        }<br>    }<br><br>    @Then(&quot;result must be {double}&quot;)<br>    public void thenResultMustBe(Number result) {<br>        assertEquals(result, this.result.getResult());<br>    }<br><br>    @Then(&quot;an exception is thrown with message {string}&quot;)<br>    public void thenExceptionIsThrown(String expectedMessage) {<br>        assertNotNull(exception);<br>        assertEquals(expectedMessage, exception.getMessage());<br>    }<br>}</pre><p>This file is where all the logic to run the application BDD tests are like instantiate our service class, build the payloads and check the result.</p><p>addition_calculation.feature</p><pre>Feature: Addition is calculated between two numbers<br>  Scenario: Two numbers addition<br>    Given operator is 3.0 and operand is 2.0 and operation is &quot;ADDITION&quot;<br>    When calculation is performed<br>    Then result must be 5.0<br><br>  Scenario: Two negative numbers addition<br>    Given operator is -3.0 and operand is -2.0 and operation is &quot;ADDITION&quot;<br>    When calculation is performed<br>    Then result must be -5.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is 3.0 and operand is -2.0 and operation is &quot;ADDITION&quot;<br>    When calculation is performed<br>    Then result must be 1.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is -3.0 and operand is 2.0 and operation is &quot;ADDITION&quot;<br>    When calculation is performed<br>    Then result must be -1.0</pre><p>division_calculation.feature</p><pre>Feature: Division is calculated between two numbers<br>  Scenario: Two numbers multiplication<br>    Given operator is 4.0 and operand is 2.0 and operation is &quot;DIVISION&quot;<br>    When calculation is performed<br>    Then result must be 2.0<br><br>  Scenario: Two negative numbers multiplication<br>    Given operator is -4.0 and operand is -2.0 and operation is &quot;DIVISION&quot;<br>    When calculation is performed<br>    Then result must be 2.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is 4.0 and operand is -2.0 and operation is &quot;DIVISION&quot;<br>    When calculation is performed<br>    Then result must be -2.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is -4.0 and operand is 2.0 and operation is &quot;DIVISION&quot;<br>    When calculation is performed<br>    Then result must be -2.0<br><br>  Scenario: Division by zero<br>    Given operator is 2.0 and operand is 0.0 and operation is &quot;DIVISION&quot;<br>    When calculation is performed<br>    Then an exception is thrown with message &quot;zero division not permitted&quot;</pre><p>multiplication_calculation.feature</p><pre>Feature: Multiplication is calculated between two numbers<br>  Scenario: Two numbers multiplication<br>    Given operator is 3.0 and operand is 2.0 and operation is &quot;MULTIPLICATION&quot;<br>    When calculation is performed<br>    Then result must be 6.0<br><br>  Scenario: Two negative numbers multiplication<br>    Given operator is -3.0 and operand is -2.0 and operation is &quot;MULTIPLICATION&quot;<br>    When calculation is performed<br>    Then result must be 6.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is 3.0 and operand is -2.0 and operation is &quot;MULTIPLICATION&quot;<br>    When calculation is performed<br>    Then result must be -6.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is -3.0 and operand is 2.0 and operation is &quot;MULTIPLICATION&quot;<br>    When calculation is performed<br>    Then result must be -6.0</pre><p>subtraction_calculation.feature</p><pre>Feature: Subtraction is calculated between two numbers<br>  Scenario: Two numbers subtraction<br>    Given operator is 3.0 and operand is 2.0 and operation is &quot;SUBTRACTION&quot;<br>    When calculation is performed<br>    Then result must be 1.0<br><br>  Scenario: Two negative numbers subtraction<br>    Given operator is -3.0 and operand is -2.0 and operation is &quot;SUBTRACTION&quot;<br>    When calculation is performed<br>    Then result must be -1.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is 3.0 and operand is -2.0 and operation is &quot;SUBTRACTION&quot;<br>    When calculation is performed<br>    Then result must be 5.0<br><br>  Scenario: One positive number and one negative number<br>    Given operator is -3.0 and operand is 2.0 and operation is &quot;SUBTRACTION&quot;<br>    When calculation is performed<br>    Then result must be -5.0</pre><p>These are all the .feature files that define the test values and expected results. Once everything is set up, just open a terminal and type: <strong><em>gradle cucumberCli. </em></strong>This will start running the Cucumber tests.</p><p>Remember to check the file paths in build.gradle, otherwise, an error may occur.</p><p>I won’t add all the Java application files here to keep this tutorial concise, but you can check the bibliography below for the link to the repository where all the code is available.</p><p>Thanks for reading, and I expect to help some of you guys that arrived here! Focus on the journey to be a better dev every day! Have a nice day!</p><h4>Bibliography</h4><ul><li><a href="https://github.com/AugustoKlaic/Java-Series/tree/master/bdd-basics">Java-Series/bdd-basics at master · AugustoKlaic/Java-Series</a></li><li><a href="https://cucumber.io/docs/bdd/">Behaviour-Driven Development | Cucumber</a></li><li><a href="https://cucumber.io/docs">Introduction | Cucumber</a></li><li><a href="https://cucumber.io/docs/guides/10-minute-tutorial">10-minute tutorial | Cucumber</a></li></ul><p><a href="https://www.baeldung.com/java-cucumber-gradle">https://www.baeldung.com/java-cucumber-gradle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ffc19d7bd2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>