<?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 Sominda Gamage on Medium]]></title>
        <description><![CDATA[Stories by Sominda Gamage on Medium]]></description>
        <link>https://medium.com/@somindagamage?source=rss-ff0a15b74cca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gjFN3lvtYiHxN9oh</url>
            <title>Stories by Sominda Gamage on Medium</title>
            <link>https://medium.com/@somindagamage?source=rss-ff0a15b74cca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somindagamage/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[Spring Boot for Beginners: gRPC with Spring Boot]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-grpc-with-spring-boot-9de4ae2a0937?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de4ae2a0937</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 15:47:44 GMT</pubDate>
            <atom:updated>2025-04-12T15:47:44.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image credits: https://blog.nashtechglobal.com/what-is-grpc-protocol-buffers-streaming-and-architecture/" src="https://cdn-images-1.medium.com/max/1024/1*wuI0edsZAIh1HB-jEhnq6Q.jpeg" /></figure><p>If you’ve ever built APIs using REST and wondered if there’s a faster, more efficient way to communicate between services 🤔 Say hello to <strong>gRPC</strong>!</p><p>Built on HTTP/2 and powered by Protocol Buffers, gRPC is a high-performance, language-agnostic RPC (Remote Procedure Call) framework that’s perfect for microservices, real-time applications, and systems where speed and efficiency matters.</p><p>But this isn’t another “What is gRPC?” article. Instead, I want to show you just how easy it is to spin up a gRPC server using Spring Boot, without drowning in boilerplate code. Clean, simple, and powerful. Let’s dive in!</p><p>For this sample, I’ll be using my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners">demo Spring Boot project</a>. If you’ve missed my previous articles on Spring Boot, be sure to check them out <a href="https://github.com/somindatommy/SpringBoot-For-Beginners?tab=readme-ov-file#articles">here</a> as there is some good stuff in there! 😄</p><p>So what am I thinking here? In the last few articles, everything was built around a single server handling all the logic. But today, I’m thinking bigger. It’s time to split things up a bit! Here’s the plan 🧠, the REST server we developed earlier will now focus solely on interacting with the user (think UI and external API calls). The server I’m building today will take charge of <strong>all database operations</strong>. Yep, this new service will own all the CRUD logic and expose its functionality through gRPC so that any other service can consume it easily. This approach gives us a clean separation of concerns and sets the stage for a more scalable architecture. Let’s keep this architecture in mind as we move through the rest of this article.</p><p>Today, I’m kicking things off from the choreo-integration <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/choreo-integration">branch</a>, since I’ve got plans to deploy this to WSO2 Choreo. Let’s get coding 🚀.</p><p>Alright, let’s start at a familiar place: <a href="https://start.spring.io/">Spring Initializr</a>. As shown in the picture, I’ll be creating a new module and adding the <strong>Spring gRPC</strong> dependency. Yes, it’s marked as experimental, but no worries, it still packs all the features we need to get going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_sVlC0IkPkuQS_6qUxCYw.png" /></figure><p>Go ahead and download the generated project and take a quick peek inside. You’ll see that Spring Initializr has already set up everything we need; all the necessary dependencies are in the pom.xml, and the folder structure is exactly what we’d expect. Let’s move on and start getting our hands dirty with some real code! 💪.</p><p>Now to the service definition. I’m not going into details on the structure. That is a topic for another.</p><pre>syntax = &quot;proto3&quot;;<br><br>option java_multiple_files = true;<br>option java_package = &quot;com.sominda.payments.server.generated&quot;;<br><br>package com.sominda.grpc.server.payments;<br><br>enum Status {<br>  PENDING = 0;<br>  PROCESSING = 1;<br>  SUCCESS = 2;<br>  FAILED = 3;<br>}<br><br>// Request to initiate a payment.<br>message PaymentRequest {<br>  string initiatorId = 1;<br>  string receiverId = 2;<br>  double amount = 3;<br>}<br><br>// Response after initiating a payment.<br>message InitiatePaymentResponse {<br>  string paymentId = 1;<br>  Status status = 2;<br>}<br><br>// Response to represent a payment object.<br>message PaymentResponse {<br>  string paymentId = 1;<br>  string initiatorId = 2;<br>  string receiverId = 3;<br>  double amount = 4;<br>  string initiatedTime = 5;<br>  Status status = 6;<br>}<br><br>// Request to get all payments.<br>message GetAllPaymentsRequest {<br>// Defining an empty object in case any params are needed in the future.<br>}<br><br>// Response returning a list of payments.<br>message GetPaymentsResponse {<br><br>  repeated PaymentResponse payments = 1;<br>}<br><br>// Get all payments by payment status.<br>message GetPaymentsByStatusRequest {<br>  Status status = 1;<br>}<br><br>// Get payment by id request.<br>message GetPaymentByIdRequest {<br>  string paymentId = 1;<br>}<br><br>// Server exposed APIs.<br>service PaymentServer {<br><br>  // Define unary operations.<br>  rpc getPayments(GetAllPaymentsRequest) returns (GetPaymentsResponse);<br>  rpc getPaymentById(GetPaymentByIdRequest) returns (PaymentResponse);<br>  rpc getPaymentsByStatus(GetPaymentsByStatusRequest) returns (GetPaymentsResponse);<br>  rpc initiatePayment(PaymentRequest) returns (InitiatePaymentResponse);<br>}</pre><p>I’ve gone ahead and created a few APIs that mirror the REST endpoints we built earlier on the REST server. Once the project is built, you’ll notice that all the messages and service stubs defined in our .proto files are now auto-generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*pFkzkh0k4wZ8dwHVFAaEaw.png" /></figure><p>Now, let’s roll up our sleeves and implement the server. I’ll be creating a new class and extending it from PaymentServiceGrpc. PaymentServiceImplBase;the base service class generated by the protoc compiler from our .proto file earlier. (And don’t worry, all the sample code is available in my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/spring_grpc">GitHub repository</a>! 😉)</p><pre>package com.sominda.payments.payment_manager_server.service;<br><br>import com.sominda.payments.server.generated.GetAllPaymentsRequest;<br>import com.sominda.payments.server.generated.GetPaymentByIdRequest;<br>import com.sominda.payments.server.generated.GetPaymentsByStatusRequest;<br>import com.sominda.payments.server.generated.GetPaymentsResponse;<br>import com.sominda.payments.server.generated.InitiatePaymentResponse;<br>import com.sominda.payments.server.generated.PaymentRequest;<br>import com.sominda.payments.server.generated.PaymentResponse;<br>import com.sominda.payments.server.generated.PaymentServerGrpc;<br>import io.grpc.stub.StreamObserver;<br>import org.springframework.grpc.server.service.GrpcService;<br><br>@GrpcService<br>public class PaymentServerImpl extends PaymentServerGrpc.PaymentServerImplBase {<br><br>    @Override<br>    public void getPayments(GetAllPaymentsRequest request, StreamObserver&lt;GetPaymentsResponse&gt; responseObserver) {<br><br>        System.out.println(&quot;Invoked getPayments&quot;);<br>        super.getPayments(request, responseObserver);<br>    }<br><br>    @Override<br>    public void getPaymentById(GetPaymentByIdRequest request, StreamObserver&lt;PaymentResponse&gt; responseObserver) {<br><br>        System.out.println(&quot;Invoked getPaymentById&quot;);<br>        super.getPaymentById(request, responseObserver);<br>    }<br><br>    @Override<br>    public void getPaymentsByStatus(GetPaymentsByStatusRequest request,<br>                                    StreamObserver&lt;GetPaymentsResponse&gt; responseObserver) {<br><br>        System.out.println(&quot;Invoked getPaymentsByStatus&quot;);<br>        super.getPaymentsByStatus(request, responseObserver);<br>    }<br><br>    @Override<br>    public void initiatePayment(PaymentRequest request, StreamObserver&lt;InitiatePaymentResponse&gt; responseObserver) {<br><br>        System.out.println(&quot;Invoked initiatePayment&quot;);<br>        super.initiatePayment(request, responseObserver);<br>    }<br>}</pre><p>Notice that I’ve used the @GrpcService annotation. This little gem marks the class as a gRPC service implementation, allowing Spring Boot to automatically detect and register it without all the tedious boilerplate and configuration.</p><p>Before diving into the complete implementation, let’s test and see if our server is actually working. To kick things off, I’ll go ahead and update the application.properties with the server configurations.</p><pre>spring.application.name=payment-manager-server<br><br>grpc.server.address=localhost:9090  # Set the server to listen on port 9090<br>grpc.server.security.enabled=false  # Disable security (TLS)</pre><p>Notice that I’ve disabled TLS authentication for this one since this is just a demo. I’ll dive into TLS implementation another day (fingers crossed!). But, a quick pro-tip: when you’re building a production system, <strong>ALWAYS</strong> enable TLS for secure communication. 🔒</p><p>Now, go ahead and run the PaymentManagerServerApplication and check out the following startup logs. You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TdDGzT8J6J6Un16HYDWsg.png" /></figure><p>Now go ahead and import the proto definition into Postman. Postman is my go-to tool when playing around with APIs, and it’s super handy for testing gRPC calls too.</p><p>Once you hit that request, you’ll probably see a 12 UNIMPLEMENTED error. This is expected as we haven’t implemented the actual logic yet. So, how do we know if things are wired up correctly? Just check the server logs for those print statements we added earlier. See them? 🎉 Boom! You’ve successfully stood up a gRPC server. That wasn’t too bad, right?</p><p>Now what’s left is hooking this up to the database. But I won’t dive deep into that here because if you’ve been following along, you already know I’ve covered that part in a <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/swagger-integration?tab=readme-ov-file#articles">previous article</a>. 😉 Instead, let me just show you how I overrode the service methods to wire everything up:</p><pre>package com.sominda.payments.payment_manager_server.service;<br><br>import com.sominda.payments.server.generated.GetAllPaymentsRequest;<br>import com.sominda.payments.server.generated.GetPaymentByIdRequest;<br>import com.sominda.payments.server.generated.GetPaymentsByStatusRequest;<br>import com.sominda.payments.server.generated.GetPaymentsResponse;<br>import com.sominda.payments.server.generated.InitiatePaymentResponse;<br>import com.sominda.payments.server.generated.PaymentRequest;<br>import com.sominda.payments.server.generated.PaymentResponse;<br>import com.sominda.payments.server.generated.PaymentServerGrpc;<br>import com.sominda.payments.payment_manager_server.model.Payment;<br>import com.sominda.payments.payment_manager_server.repository.PaymentsJPARepository;<br>import io.grpc.stub.StreamObserver;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.grpc.server.service.GrpcService;<br><br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.Optional;<br><br>import static com.sominda.payments.payment_manager_server.util.PaymentMapper.toProto;<br><br>@GrpcService<br>public class PaymentServerImpl extends PaymentServerGrpc.PaymentServerImplBase {<br><br>    @Autowired<br>    private PaymentsJPARepository paymentsJPARepository;<br><br>    @Override<br>    public void getPayments(GetAllPaymentsRequest request, StreamObserver&lt;GetPaymentsResponse&gt; responseObserver) {<br><br>        List&lt;Payment&gt; payments = paymentsJPARepository.findAll();<br>        List&lt;PaymentResponse&gt; paymentResponses = new ArrayList&lt;&gt;();<br><br>        for (Payment payment : payments) {<br>            paymentResponses.add(toProto(payment));<br>        }<br>        GetPaymentsResponse.Builder builder = GetPaymentsResponse.newBuilder();<br>        builder.addAllPayments(paymentResponses);<br><br>        responseObserver.onNext(builder.build());<br>        responseObserver.onCompleted();<br>    }<br><br>    @Override<br>    public void getPaymentById(GetPaymentByIdRequest request, StreamObserver&lt;PaymentResponse&gt; responseObserver) {<br><br>        Optional&lt;Payment&gt; payments = paymentsJPARepository.findById(request.getPaymentId());<br>        if (payments.isPresent()) {<br>            responseObserver.onNext(toProto(payments.get()));<br>            responseObserver.onCompleted();<br>        }<br>        // Handle error.<br>    }<br><br>    @Override<br>    public void getPaymentsByStatus(GetPaymentsByStatusRequest request,<br>                                    StreamObserver&lt;GetPaymentsResponse&gt; responseObserver) {<br><br>        List&lt;Payment&gt; payments = paymentsJPARepository.findAllPaymentsByStatus(request.getStatus());<br>        List&lt;PaymentResponse&gt; paymentResponses = new ArrayList&lt;&gt;();<br><br>        for (Payment payment : payments) {<br>            paymentResponses.add(toProto(payment));<br>        }<br>        GetPaymentsResponse.Builder builder = GetPaymentsResponse.newBuilder();<br>        builder.addAllPayments(paymentResponses);<br><br>        responseObserver.onNext(builder.build());<br>        responseObserver.onCompleted();<br>    }<br><br>    @Override<br>    public void initiatePayment(PaymentRequest request, StreamObserver&lt;InitiatePaymentResponse&gt; responseObserver) {<br><br>        Payment payment = Payment.create(request.getInitiatorId(), request.getReceiverId(), request.getAmount());<br>        paymentsJPARepository.save(payment);<br>        InitiatePaymentResponse.Builder builder = InitiatePaymentResponse.newBuilder();<br>        builder.setPaymentId(payment.getPaymentId());<br>        builder.setStatus(payment.getStatus());<br>        responseObserver.onNext(builder.build());<br>        responseObserver.onCompleted();<br>    }<br>}</pre><p>IMO, this part of the implementation is super straightforward, so I won’t go into too much detail here. For the database, I’m using <strong>H2</strong> with <strong>Spring Data JPA,</strong> keeping things nice and simple for demo purposes.</p><p>Here are the application.properties configurations I&#39;m using:</p><pre>spring.application.name=payment-manager-server<br><br>grpc.server.address=localhost:9090  # Set the server to listen on port 9090<br>grpc.server.security.enabled=false  # Disable security (TLS)<br><br>###### H2 Database related configurations ######<br># Access the h2 console from browser.<br>spring.h2.console.enabled=true<br>spring.datasource.generate-unique-name=false<br>spring.datasource.name=Payments_Db<br>spring.datasource.username=sa<br>spring.datasource.password=sa<br><br># Add this when the script needs to execute. Usually this is done for the H2 in-memory dbs.<br>spring.sql.init.mode=always<br>spring.sql.init.schema-locations=classpath:dbscripts/h2/schema.sql<br><br>#### JPA configurations<br>spring.datasource.url=jdbc:h2:mem:Payments_Db<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect<br># Since we have added JPA, spring handles initiation differently. This is added so that initial deta insertion may<br># happen as expected.<br>spring.jpa.hibernate.ddl-auto=update<br><br># Rest server just to check the h2 console.<br>server.port=8080</pre><p>One last thing! You might’ve noticed that I also started a web server on port 8080. That’s because I wanted to check out the H2 Console (If you’re trying this too, don’t forget to add the <strong><em>Spring Boot Starter Web</em></strong> dependency to your pom.xml).</p><p>I also made a few improvements to the object mappings and model classes to keep things clean and smooth. You can check out all those changes in my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/spring_grpc">GitHub repo</a>; feel free to explore, clone, and run it yourself.</p><p>Alright, now that everything’s wired up, let’s start the server, fire up Postman, and test away! Everything working? Boom 💥! You just built a fully functional gRPC service with Spring Boot, complete with database integration and minimal boilerplate.</p><p>That’s the real power of <strong>Spring Boot</strong>. It takes care of the repetitive stuff, so <em>you</em> can focus on what really matters, which is building the awesome business logic.</p><p>If you’re thinking about writing tests for your gRPC server, make sure to check out <a href="https://medium.com/@AlexanderObregon/getting-started-with-grpc-in-spring-boot-using-the-grpcservice-annotation-2decabbb3a02">this awesome blog</a> that covers the essentials. It’s a great place to start until I drop my own deep-dive guide on testing with Spring Boot. Stay tuned! 😉</p><p>That’s it from me today! I really hope you learned something valuable from this article. If you’re doing things differently or have any cool tips or tricks, I’m all ears — feel free to share in the comments! 😊</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/spring_grpc">GitHub repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><h4>🚀 <strong>What’s Next?</strong></h4><p>In the next article, I’ll walk you through how to implement the <strong>gRPC client</strong>. I will be covering everything together so our previous REST server can talk to the gRPC service behind the scenes. In the meantime, feel free to check out my <a href="https://somindagamage.medium.com/list/introduction-to-spring-boot-24d11c2d65eb"><strong>Spring Boot article collection</strong></a> to catch up on what we’ve done so far.</p><p>Stay tuned, more cool stuff coming soon! 😄</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de4ae2a0937" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Role-Based Access Control with Choreo and Asgardeo]]></title>
            <link>https://somindagamage.medium.com/role-based-access-control-with-choreo-and-asgardeo-606d72a7353e?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/606d72a7353e</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[asgardeo]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[choreo]]></category>
            <category><![CDATA[rbac]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 19:50:46 GMT</pubDate>
            <atom:updated>2025-03-31T19:50:46.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWG80GbhB_DIn0yAZAO0aA.jpeg" /></figure><p>As promised in my <a href="https://somindagamage.medium.com/deploying-a-spring-boot-application-on-choreo-c37bf72d353d">previous article</a>, today I’m diving into <strong>adding RBAC (Role-Based Access Control)</strong> to the service I deployed earlier! 🔐</p><p>RBAC is a crucial step in securing our APIs, ensuring that only the right users have access to specific actions. In this guide, I’ll walk you through integrating <strong>Asgardeo</strong> with Choreo to enforce RBAC in our Spring Boot service.</p><p>If you’re following along with my <strong>Spring Boot for Beginners</strong> series, be sure to check out all my articles <a href="https://github.com/somindatommy/SpringBoot-For-Beginners?tab=readme-ov-file#deploying-in-cloud">here</a>.</p><p>I’ve been exploring different ways to tackle this, but today, I’ll <strong>focus on one approach</strong>. 🚀 Hopefully, I’ll find time to dive into other methods in the future (fingers crossed! 🤞).</p><p>Let’s get into it! 🔥</p><p>I’m going to start from where I left in the last article. So we have deployed a service and disabled any authorization to access the APIs.</p><p>First we need to add <strong>Asgardeo as an External IDP</strong>. But guess what? It should already be there by default! Just to be sure, head over to <strong>Organization Settings &gt; Application Security</strong> and verify it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oA3jPmNWW-aCwBnKBD4hA.png" /></figure><p>Now, let’s jump back into our Choreo project! 🚀</p><ul><li>Head over to the project and navigate to the component that we deployed earlier.</li><li>In the left-hand pane, click on the <strong>Deploy</strong> tab.</li><li>Now, find and click on <strong>Endpoint Configurations</strong> to edit the authorization settings.</li></ul><p>Time to lock things down with some proper access control! 🔒😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZfnZVD-xwWkpkLOcXBkDQ.png" /></figure><p>Here are the <strong>configurations</strong> I’ve updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0f0YXGU1ENggRnMZDskG5Q.png" /></figure><p>I’ve enabled <strong>OAuth2</strong> and added two new scopes:</p><ul><li><strong>payments_init</strong> — To initiate payments</li><li><strong>payments_list</strong> — To list payments</li></ul><p>Then, I applied <strong>scope validation</strong> only for:<br> ✅ <strong>POST /payments</strong> — Requires payments_init <br> ✅ <strong>GET /payments/{id}</strong> – Requires payments_list</p><p>Other endpoints remain open to demonstrate how things work without scope validation. Once done, just hit <strong>Apply</strong>! 🚀🔐 Now, let’s promote the endpoint configurations to the development environment by clicking on <strong><em>Deploy</em></strong>. Once that’s done, go ahead and promote it to production by clicking the <strong><em>Promote</em></strong> button. 🚀</p><p>Once the production deployment is complete, try invoking the <strong>GET /payments</strong> API (or any other API) and notice that access is now <strong>restricted</strong>! 🔒 No more unauthorized access; just how we want it! 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LtixuWTooH15OYuqzOh5og.png" /></figure><pre>{&quot;error_message&quot;:&quot;The access token is not authorized to access the environment.&quot;,&quot;code&quot;:&quot;900912&quot;,&quot;error_description&quot;:&quot;The access token is not authorized to access the environment.&quot;}</pre><p>First, let’s make our APIs visible to the outside world! Head over to <em>Manage &gt; Lifecycle</em> from the left-hand pane and click <strong><em>Publish</em></strong>. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SsEMqOrp_XBsVwmICTh_EA.png" /></figure><p>Once Successful, it should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*2aI-2YOguERxxeRRqvgXHw.png" /></figure><p>Now, let’s head over to the <a href="https://devportal.choreo.dev/"><strong>Choreo Developer Portal</strong></a>!</p><p>1️⃣ Go to the <strong><em>Applications</em> </strong>tab and create a new application.<br>2️⃣ Head over to<strong> <em>Subscriptions</em></strong> and click on <strong><em>Add APIs</em></strong>.<br>3️⃣ From the dropdown, select the published API, choose a subscription plan, and click <strong><em>Add Subscription</em></strong>.<br>4️⃣ Copy all the scopes for this subscription either by clicking <strong>Copy Scopes</strong> or manually copying them from the API details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AALpfYVB25T4l3dYUALW3Q.png" /></figure><p>5️⃣ Now, go to <strong><em>Credentials &gt; Production</em></strong>, then click on <strong><em>Advanced Configurations. </em></strong>Here, I’ve adjusted the token expiry times just for demo purposes. Feel free to experiment! 😏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*zV_kfNxDGSWYsRNdSpy4nA.png" /></figure><p>6️⃣ Finally, click <strong><em>Generate Credentials</em></strong> and then <strong><em>Generate Token</em></strong>.<br>7️⃣ Paste the copied scopes in the scope section before generating the token. If you don’t see a place to provide scopes, go back to the <strong><em>Applications</em> </strong>tab, navigate to <strong><em>Credentials</em></strong>, and click <strong><em>Generate Token</em></strong> again (Yep, there’s a weird issue here 🤷‍♂️).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*llafExmgWLmciSya0CZEGA.png" /></figure><p>📝 <strong>NOTE: </strong>There’s a good chance that you won’t see <strong>“Response Permissions”</strong> when generating the token. This happens because the <strong>API Authorization</strong> hasn’t been configured in the <strong>Asgardeo Application</strong> yet. Don’t worry, I’ll walk you through those steps soon. In the meantime, test the APIs without scope validation as the missing response won’t affect!</p><p>Now, with your new token, we can access the secured APIs! 🚀 Next, open <strong>Postman</strong>, go to <strong><em>Authorization</em></strong>, select <strong><em>Bearer Token</em></strong>, and paste the token. Now, try sending a request… and boom! <strong>It worked!</strong> You should now see a successful response. 🔥</p><p>To fully configure <strong>RBAC for users</strong>, we need to tweak a few more settings in <strong>Asgardeo</strong>. For that, let’s hop over to the <a href="https://console.asgardeo.io/"><strong>Asgardeo organization</strong></a>. There is no need to manually create an organization there; when you set up a Choreo organization, a corresponding Asgardeo organization is automatically created for you. Just a heads-up: if you have multiple Asgardeo organizations, make sure you’re in the same one as your Choreo setup!</p><p>Now, go to <strong><em>API Resources </em></strong>from the left-hand pane in Asgardeo. You’ll see that Choreo has already configured some settings for you! Take a moment to click around and explore what’s been set up.</p><p>Next, go to the <strong><em>Applications</em></strong> section in Asgardeo. You’ll see an application with the same name you used in the Choreo Developer Portal. Click on it and navigate to the <strong><em>API Authorization</em></strong> tab. Now, click on <strong><em>Authorize API Resource</em></strong>, select the <strong>API resource that was created earlier</strong>, check all the scopes, and hit <strong><em>Finish</em></strong>. Now, your app is officially authorized to request these scopes. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*yCW_y9vG9Oj9IePhGJHn2Q.png" /></figure><p>In the same application settings, navigate to the <strong><em>Roles</em></strong> tab and set <strong><em>Organization</em></strong> as the <strong><em>Role Audience</em></strong>. Why? 🤔 Because I’m planning to create Organization roles and assign them to specific users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdTQdI1LRNAYV-r3uhkh1g.png" /></figure><p>Now, let’s set up some <strong>Organization roles</strong> and bind them to our scopes! I’m creating two roles:<br> 👩‍💼 <strong>Cashier</strong> → Assigned the payments_init scope (can initiate payments).<br> 👨‍💼 <strong>Manager</strong> → Assigned the payments_list scope (can list payments).</p><p>This way, only users with the Cashier role can initiate payments, and only Managers can list them. Sounds fair, right? 😏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*14SOgS_x2g2WjfV5NZU0MQ.png" /></figure><p>Now that the roles are assigned, let’s generate a new token from the Choreo App. Once you have the token, go ahead and try out any API… and boom! It works exactly as expected. 🎯</p><p>Now let’s try with the users. For that, let’s use the <strong>password grant type</strong>! We’ll need:</p><ul><li><strong>Consumer Key &amp; Secret</strong> from the application created in Choreo (same as the Client ID &amp; Secret in Asgardeo Application).</li><li><strong>Token endpoint URL</strong> (available in both Choreo &amp; Asgardeo app settings).</li></ul><p>Here’s a sample curl command to request a token:</p><pre>curl --location &#39;https://api.asgardeo.io/t/integratechoreo/oauth2/token&#39; \<br>--header &#39;Content-Type: application/x-www-form-urlencoded&#39; \<br>--header &#39;Authorization: Basic base64Encode&lt;client_id:client_ecret&gt;&#39; \<br>--header &#39;Cookie: wpaf=1743387975.57.191.342554|71acb898e1e9604d7bd8c41e308eb24e&#39; \<br>--data-urlencode &#39;grant_type=password&#39; \<br>--data-urlencode &#39;scope=payments_list&#39; \<br>--data-urlencode &#39;username=manager@mnc.com&#39; \<br>--data-urlencode &#39;password=&lt;password&gt;&#39;</pre><p>Here, I have added the payments_list scope and used the <strong>Base64 encoded</strong> client_id and client_secret. Now, let’s put our tokens to the test! 🛠️</p><p>1️⃣ Use the token from the<strong> Manager </strong>role and invoke any <strong><em>GET /payments</em></strong> request. ✅ It should pass since Managers are allowed to list payments.</p><p>2️⃣ Now, try the <strong>POST </strong>request to<strong> initiate a payment.</strong> Notice the <strong>HTTP 403 Forbidden</strong> error. That’s expected because Managers don’t have permission to initiate payments.</p><p>3️⃣ Switch to the<strong> Cashier user, </strong>get a token<strong> </strong>and try again:</p><ul><li><strong>POST request?</strong> ✅ It worked as the Cashiers have the payments_init scope.</li><li><strong>GET payment by ID?</strong> ❌ Failed because the Cashiers don’t have the payments_list scope.</li></ul><p>And there you have it! 🎉 <strong>RBAC is now fully functional in Choreo with Asgardeo.</strong> 🚀</p><p>And that’s it for today! 🎉 I really hope you learned something valuable from this article. If you’re doing things differently or have any cool tips or tricks, I’m all ears; feel free to share in the comments! 😊</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/choreo-integration">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=606d72a7353e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Spring Boot Application on Choreo]]></title>
            <link>https://somindagamage.medium.com/deploying-a-spring-boot-application-on-choreo-c37bf72d353d?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c37bf72d353d</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[choreo]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[wso2]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 00:21:17 GMT</pubDate>
            <atom:updated>2025-03-18T00:21:17.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBDdZB7w2R9pA8Jxm-ee2w.png" /></figure><p>While back, I was writing an article on <a href="https://somindagamage.medium.com/spring-boot-for-beginners-securing-the-apis-with-tokens-586d3c13700d">securing APIs with tokens</a> for Spring Boot services. While working on it, I wondered, why not deploy this on <a href="https://wso2.com/choreo/">WSO2 Choreo</a> and leverage Choreo with <a href="https://wso2.com/asgardeo/">Asgardeo</a> to secure the APIs and do even more? 🤔 Well, I decided to give it a shot! So, to kick things off, I’m first going to deploy the web server on Choreo and test it out. Let’s dive in! 🚀</p><h3>What the heck is WSO2 Choreo</h3><p>Haha, gotta love how tech names always sound so futuristic! Anyway, WSO2 <strong>Choreo is a cloud-native integration platform as a service (iPaaS) </strong>that makes it super easy to develop, deploy, and manage APIs, integrations, and microservices.</p><p>The best way to understand what Choreo is? Spend 4 minutes watching <a href="#">this video</a> (trust me, it’s worth it!).</p><p>And no, the Choreo guys aren’t sponsoring this article (though I totally wouldn’t mind if they did 😉). I’m just giving it a go because it looks pretty cool and, well, I’m an ex-WSO2 employee, so curiosity got the best of me!</p><p>Here’s what I’m thinking. I’ll start with a super basic webserver deployment to expose the REST endpoints. For now, I’m keeping things simple by disabling the authentication and using H2. Later, I’ll look into integrating with Asgardeo and enabling RBAC for the APIs (but that might be a whole separate article 😉).</p><p>To do this, I’ll use the <a href="https://github.com/somindatommy/SpringBoot-For-Beginners">Spring Boot webserver</a> I built earlier, along with the Dockerfiles from <a href="https://somindagamage.medium.com/spring-boot-for-beginners-deploying-the-server-in-docker-fee07992adc2">my previous article</a>. Let’s get to it!</p><p>First, I want to keep the server as simple as possible. No fancy configs, no unnecessary complexity. Why? Because this is just a demo! Duh. 😆</p><ul><li>Disable the token validation we implemented earlier.</li><li>Switch to H2 by setting the profiles to Dev,H2Repo and uncommenting the H2 configs.</li><li>Comment out MySQL-specific configurations.</li><li>Update pom.xml to change the H2 dependency scope to runtime</li></ul><p><strong>NOTE:</strong> check out my <a href="https://somindagamage.medium.com/spring-boot-for-beginners-deploying-the-server-in-docker-fee07992adc2">previous article</a> for details on these steps.</p><p>Next, let’s tackle the requirements for deployment. According to the <a href="https://wso2.com/choreo/docs/develop-components/develop-services/develop-a-service-with-docker/">Choreo docs</a>, I need the following three files in my repository for deployment. Let’s see what they are! ⏬</p><ul><li>Dockerfile — This is what we use to build the Docker image for our Spring Boot application.</li><li>.choreo/component.yaml — This is a Choreo-specific configuration file that tells Choreo how to expose our service.</li><li>openapi.yaml — This is the API definition file.</li></ul><p>Alright, let’s kick things off by generating our API definition! First, we need to add the <strong>springdoc-openapi</strong> dependency to our pom.xml. This will allow us to automatically generate an OpenAPI definition based on our Spring Boot REST endpoints.</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br> &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br> &lt;version&gt;2.8.5&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Now, go ahead and restart the server and visit the following link to check out the generated API definition:</p><p>📌 http://localhost:8080/v3/api-docs — to view OpenAPI spec in JSON format.<br> 📌 http://localhost:8080/swagger-ui.html — to get the interactive Swagger UI to test the APIs.</p><p>📌 http://localhost:8080/api-docs.yaml — to get OpenAPI spec in YAML format.</p><p>Head over to the following 3rd link and download the API definition. Once downloaded, save the file as openapi.yaml inside the payment-manager directory. Before moving forward, open the file and double-check that the OpenAPI version is set to <strong>3.0.1</strong>.</p><pre>openapi: 3.0.1<br>info:<br>  title: OpenAPI definition<br>  version: v0<br>servers:<br>- url: http://localhost:8080<br>  description: Generated server url<br>paths:<br>  /api/v1/payments:<br>    get:<br>      tags:<br>      - payment-controller<br>      operationId: getAllPayment<br>      responses:<br>        &quot;500&quot;:<br>          description: Internal Server Error<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;400&quot;:<br>          description: Bad Request<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;200&quot;:<br>          description: OK<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &quot;#/components/schemas/Payment&quot;<br>    post:<br>      tags:<br>      - payment-controller<br>      operationId: payUser<br>      requestBody:<br>        content:<br>          application/json:<br>            schema:<br>              $ref: &quot;#/components/schemas/PaymentRequest&quot;<br>        required: true<br>      responses:<br>        &quot;500&quot;:<br>          description: Internal Server Error<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;400&quot;:<br>          description: Bad Request<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;201&quot;:<br>          description: Created<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/PaymentInitiatorResponse&quot;<br>  /api/v1/payments/{id}:<br>    get:<br>      tags:<br>      - payment-controller<br>      operationId: getPaymentById<br>      parameters:<br>      - name: id<br>        in: path<br>        required: true<br>        schema:<br>          type: string<br>      responses:<br>        &quot;500&quot;:<br>          description: Internal Server Error<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;400&quot;:<br>          description: Bad Request<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;200&quot;:<br>          description: OK<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/Payment&quot;<br>  /api/v1/payments/status/{status}:<br>    get:<br>      tags:<br>      - payment-controller<br>      operationId: getPaymentsByStatus<br>      parameters:<br>      - name: status<br>        in: path<br>        required: true<br>        schema:<br>          type: string<br>      responses:<br>        &quot;500&quot;:<br>          description: Internal Server Error<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;400&quot;:<br>          description: Bad Request<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;200&quot;:<br>          description: OK<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &quot;#/components/schemas/Payment&quot;<br>  /api/v1/payments/authdata:<br>    get:<br>      tags:<br>      - payment-controller<br>      operationId: getAuthentication<br>      responses:<br>        &quot;500&quot;:<br>          description: Internal Server Error<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;400&quot;:<br>          description: Bad Request<br>          content:<br>            &#39;*/*&#39;:<br>              schema:<br>                $ref: &quot;#/components/schemas/ErrorResponse&quot;<br>        &quot;200&quot;:<br>          description: OK<br>components:<br>  schemas:<br>    ErrorResponse:<br>      type: object<br>      properties:<br>        code:<br>          type: string<br>        message:<br>          type: string<br>        description:<br>          type: string<br>    PaymentRequest:<br>      type: object<br>      properties:<br>        initiator:<br>          type: string<br>        receiver:<br>          type: string<br>        amount:<br>          type: number<br>          format: double<br>    PaymentInitiatorResponse:<br>      type: object<br>      properties:<br>        paymentId:<br>          type: string<br>        status:<br>          type: string<br>          enum:<br>          - PENDING<br>          - PROCESSING<br>          - SUCCESS<br>          - FAILED<br>    Payment:<br>      type: object<br>      properties:<br>        paymentId:<br>          type: string<br>        initiatorId:<br>          type: string<br>        receiverId:<br>          type: string<br>        amount:<br>          type: number<br>          format: double<br>        initiatedTime:<br>          type: string<br>          format: date-time<br>        status:<br>          type: string<br>          enum:<br>          - PENDING<br>          - PROCESSING<br>          - SUCCESS<br>          - FAILED</pre><p>Now, let’s create the component.yaml file. As I mentioned earlier, this file tells Choreo how to expose our endpoints to the outside world. If you want to dive deeper into the details, you can check out <a href="https://wso2.com/choreo/docs/develop-components/configure-endpoints/">this doc</a>. But for now, I’ll give you a quick rundown of what we need in this file.</p><p>First, let’s set things up properly. Create a folder called .choreo inside the payment-manager directory. This is because I want to use payment-manager as the context root for our webserver. Inside .choreo, create an empty file named component.yaml. Now, <strong>a</strong>dd the following configuration to it. Make sure to align the code properly.</p><pre># +required The configuration file schema version<br>schemaVersion: 1.1<br><br># +optional Incoming connection details for the component<br>endpoints:<br>  # +required Unique name for the endpoint.<br>  # This name will be used when generating the managed API<br>  - name: payment-manager<br>    # +optional Display name for the endpoint.<br>    displayName: Payment Manager APIs<br>    service:<br>      # +optional Base path of the API that gets exposed via the endpoint.<br>      # This is mandatory if the endpoint type is set to REST or GraphQL.<br>      basePath: /<br>      # +required Numeric port value that gets exposed via the endpoint<br>      port: 8080<br>    # +required Type of traffic that the endpoint is accepting.<br>    # Allowed values: REST, GraphQL, GRPC, TCP, UDP.<br>    type: REST<br>    # +optional Network level visibilities of the endpoint.<br>    # Accepted values: Project|Organization|Public(Default).<br>    networkVisibilities:<br>      - Public<br>    # +optional The path to the schema definition file.<br>    # Defaults to wildcard route if not specified.<br>    # This is only applicable to REST endpoint types.<br>    # The path should be relative to the docker context.<br>    schemaFilePath: openapi.yaml</pre><p>Take a look at the comments in the component.yaml file as they’ll give you a quick breakdown of what each configuration does. If you want to dive deeper, check out <a href="https://wso2.com/choreo/docs/develop-components/manage-component-source-configurations/#overview-of-the-componentyaml-file">this doc</a>.</p><p>⚡ <strong>Important:</strong> Pay close attention to the schemaFilePath config! This should point to the OpenAPI definition file (openapi.yaml) we generated earlier. Make sure the path is <strong>relative to </strong>the<strong> </strong>payment-manager<strong> </strong>directory.</p><p>Now, let’s improve the Dockerfile! I’m going to copy over the content from the previous Dockerfile, make a few tweaks, and save it as a new Dockerfile inside the dockerfiles directory (Don’t worry, I’ll make sure to add all the code to my Git repository, so you can easily access it 😎).</p><pre># This needs to run from the project root. That is SpringBoot-For-Beginners directory<br># Use a Maven image to build the JAR. Use alpine to reduce the size of the image.<br>FROM maven:3.9.9-eclipse-temurin-21-alpine AS builder<br><br>WORKDIR /app<br><br># Copy the Maven project files. Use relative paths from SpringBoot-For-Beginners directory<br>COPY pom.xml .<br>COPY src ./src<br><br># Build the application. No need to run tests.<br>RUN mvn clean package -DskipTests<br><br># Use a minimal JRE image to run the app<br>FROM eclipse-temurin:21-jre-alpine<br><br># Create a new user with UID 10014<br>RUN addgroup -g 10014 choreo &amp;&amp; \<br>    adduser  --disabled-password  --no-create-home --uid 10014 --ingroup choreo choreouser<br><br>USER 10014<br><br># Copy the built JAR from the builder stage<br>COPY --from=builder /app/target/*.jar payment_manager.jar<br><br># Expose the application port<br>EXPOSE 8080<br><br># Run the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;payment_manager.jar&quot;]</pre><p>Before we move into configuring Choreo, ensure you commit the changes to Git, as we need to access the updates via GitHub. For this demo, I’ve created a new branch called <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/choreo-integration">choreo-integration</a>.</p><p>Once you’ve committed your changes, let’s proceed with deploying to Choreo:</p><ol><li>Go to <a href="https://console.choreo.dev/">Choreo Console</a> and sign in.</li><li>If it’s your first time using Choreo, you’ll be prompted to create an organization. Choose a unique name for your organization (note that this name cannot be changed later).</li><li>After that, you’ll be navigated to your default project. If you already have an existing project, you can navigate to that.</li><li>Click on the <strong>Service</strong> card to proceed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E1Cr92HspOEm2hOUyQE-g.png" /></figure><p>5. Since my code is hosted on GitHub, I’ll select the <strong>Authorize with GitHub</strong> option to link my repository. Proceed with connecting your Git account to Choreo. During the configuration, make sure to grant access to the <strong>SpringBoot-For-Beginners</strong> repository (your Spring Boot app’s repo) to enable Choreo to access your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8yufWtWx-XbiJ75WmV_sw.png" /></figure><p>6. Provide the details as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WO-GgXgI3znSCSm9S4KZdg.png" /></figure><ul><li><strong>Organization</strong>: Select the Git organization that you just connected.</li><li><strong>Public Repository</strong>: Choose the repository that contains your server implementation.</li><li><strong>Branch</strong>: Select the branch you want to connect. This can typically be the <strong>main</strong> branch.</li><li><strong>Component Directory</strong>: This is the root directory of your web server. For example, while my project directory is <strong>SpringBoot-For-Beginners</strong>, the actual server root is in the <strong>payment-manager</strong> directory. Since I want <strong>payment-manager</strong> as my context root in the files we’ve created, I need to select this directory. In your case, this can be the root directory of your project.</li><li><strong>Build Presets</strong>: Choose <strong>Docker</strong> since we are building from the Docker image.</li><li><strong>Dockerfile</strong>: Specify the path to the Dockerfile that you want to use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*ZgvCBRVFu-0MOJXKj5hVNg.png" /></figure><p>7. Provide a <strong>Component Display Name</strong> (a description is optional) and then click <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*BIoSNpkuIS927Ds8V_2obg.png" /></figure><p>You will then be navigated to the <strong>Build</strong> tab, where you can monitor the status of the image build. Click on <strong>View Details</strong> to check the progress (This step may take some time). If any errors occur, review the logs for troubleshooting. Alternatively, you can build the image locally to verify if everything works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPxcJiCzJwehzKGEs9d9DA.png" /></figure><p><strong>Note</strong>: You can always manually trigger builds or configure them to run automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWeT8pdu173uFIjWxV9NiQ.png" /></figure><p>Once the build is successful, click on <strong>Deploy</strong>. You will then be navigated to the <strong>Deploy</strong> tab, where you can see information about the deployment status of the component across different environments. Here, you can also add configurations to your build images during deployment. Now, click on <strong>Configure and Deploy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFfKO9Ki6EB7UhpyrIkvKQ.png" /></figure><p>Once you click <strong>Configure and Deploy</strong>, you will see several options. For now, we will bypass all of these, so simply click <strong>Next</strong> to proceed.</p><ul><li>Environment Configurations: for setting environment variables</li><li>File Mount: for adding Config File</li><li>Endpoint Details — endpoint details extracted from the components.yaml file.</li></ul><p>Once reviewing the above proceed by clicking the <strong>Deploy</strong> button. This will deploy the service to the <strong>Development</strong> environment, where you can test it before promoting it to higher environments. Once the deployment is successful, you will see the following screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cizDDauJJNriZ3r6HPbGmw.png" /></figure><p>Now, click on <strong><em>Test &gt; Console</em></strong> from the left-hand pane. If everything worked correctly, you should see your API definition in the <strong>OpenAPI Console</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8lDbKt1ShMOU26gEBIHWg.png" /></figure><p>Let’s test the <strong>Get All Payments</strong> API. Click on <strong>Execute</strong> and wait for the response. Note that the initial request may take some time to respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6a0DbPjg1SzarAju8w7UGw.png" /></figure><p>If this doesn’t work, go to <strong><em>DevOps &gt; Runtime</em></strong> and check the status of the pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6fjft-ZVUg39UFtifV0rw.png" /></figure><p>Congrats! 🎉 You’ve successfully deployed the app in the development environment. Now, go ahead and try out all the APIs and make sure everything’s working smoothly! 🚀</p><p>If you want to check out the logs, head over to <strong><em>Observability &gt; Runtime Logs</em></strong>. You can play around with the filters to see what options you’ve got. Also, don’t forget to check out the other observability features available here. Have fun exploring! 🔍✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5rNqiMTJEdqXvARZV52yg.png" /></figure><h3>Testing the APIs with Postman in the local machine</h3><p>Now that we’re done playing around with the Choreo console, let’s try invoking these endpoints from our laptop. 😎 Replace the <strong>localhost:8080</strong> part with the invoke URL found in the <strong><em>Test &gt; Console</em></strong> pane. You might notice you get an error.</p><pre>{&quot;error_message&quot;:&quot;Invalid Credentials&quot;,&quot;code&quot;:&quot;900901&quot;,&quot;error_description&quot;:&quot;Not a JWT token. Failed to decode the token header. Make sure you have provided the correct security credentials&quot;}</pre><p>We disabled the config in our config file, and now… what the heck is going on? 😱 This is happening because <strong>Choreo secures the API endpoints out-of-the-box</strong>. If you remember, our initial plan was to remove all the auth mechanisms, right? Let’s go ahead and disable them.</p><p>Head over to the <strong>Deploy</strong> pane and click on <strong>Endpoint Configurations</strong>. You should see something like this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyKz_Sycmi9bf9npW_-PCw.png" /></figure><p>Yep, we can do a lot of things from here! 😎 But for another day, let’s focus on achieving our original use-case. For now, let’s remove the configs and give it a try. Click on <strong>Apply</strong> to save the changes. Then, to deploy them to the development environment hit the <strong>Deploy</strong> button.</p><p>Once the deployment is successful, try the same API again. Notice that it works as expected! Now go ahead and try all the APIs from your local machine. Just keep in mind that since we’re using H2, the data might be inconsistent if a pod restart happens. ⚠️</p><p>If everything works as expected and you’re ready to promote this to production (higher environments), head over to the <strong><em>Deploy</em></strong> pane and click on the <strong>Promote</strong> button. You’ll see the same configs as when we first deployed to the Development environment. Once the production deployment is successful, you can try out the APIs using the production environment URL. You can find the URL in the Overview Pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tporUeOQ65BLPhnpjDNxlg.png" /></figure><p>Well done! 🎉 You’ve successfully deployed the web server in Choreo. Now, go ahead and check out the awesome features provided by both <strong>Asgardeo</strong> and <strong>Choreo</strong>. 🚀</p><p>And that’s it for today! 🎉 I really hope you learned something valuable from this article. If you’re doing things differently or have any cool tips or tricks, I’m all ears; feel free to share in the comments! 😊</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/choreo-integration">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c37bf72d353d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: A Step-by-Step Guide to Deploying in Docker]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-deploying-the-server-in-docker-fee07992adc2?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee07992adc2</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 01:07:04 GMT</pubDate>
            <atom:updated>2025-03-17T01:09:40.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krkTwOsazw1wNQgM1TOjNw.png" /></figure><p>In my <a href="https://medium.com/@somindagamage/spring-boot-for-beginners-generate-spring-boot-rest-api-stubs-with-swagger-66c590cc7616">last article</a>, I walked you through using Swagger with Spring Boot. If you want to check out my previous articles, feel free to explore the <a href="https://somindagamage.medium.com/list/introduction-to-spring-boot-24d11c2d65eb">Spring Boot articles</a> list. Also, all the code I write will be available in my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/main">Git repository</a>, so feel free to check it out anytime! 😄</p><p>Today, I’m diving into something that’s not strictly tied to Spring Boot but is crucial for taking your application to production.</p><p>So, we’ve built a Spring Boot application, and it runs perfectly on our local machine. But what happens when we need to deploy it somewhere else like on another computer, a cloud server, or even inside a Kubernetes cluster? That’s where Docker comes in!</p><p>Docker allows us to package our Spring Boot application into a container, ensuring it runs consistently across different environments. In this guide, I’ll focus on creating a Docker image and running our server inside a container. By the end of this article, we’ll have our Spring Boot app running smoothly inside Docker with minimal effort. Let’s get started! 🚀</p><p>First, we need to create a Dockerfile to build an image of our server. There are two ways we can do this:</p><ol><li><strong>Using released JARs</strong> — Configure releases in my Git repository and use the published JAR files.</li><li><strong>Building the JAR from the repository</strong> — Instruct docker to build the repo, and use the generated JAR.</li></ol><p>I’m going with the second approach because it’s needed for one of my future articles. So, let’s start by modifying the pom.xml file to rename our generated JAR. Add the following line inside the &lt;build&gt; section of the pom.xml:</p><pre>&lt;finalName&gt;payment_manager&lt;/finalName&gt;</pre><p>This ensures that the generated JAR file will always be named payment_manager.jar, making it easier to reference in our Dockerfile. To test the configuration, go ahead and build the artifact. Once the build is complete, check the target directory. You should see that the generated JAR file is now named payment_manager.jar.</p><p>Now, let’s move on to creating the Dockerfile! I’ll be creating a file named payment-manager-dockerfile inside a DockerFiles directory. This file will contain the instructions to build our Docker image for the Spring Boot application. Here&#39;s the sample Dockerfile to get us started:</p><pre># This needs to run from the project root. That is SpringBoot-For-Beginners directory<br># Use a Maven image to build the JAR. Use alpine to reduce the size of the image.<br>FROM maven:3.9.9-eclipse-temurin-21-alpine AS builder<br><br>WORKDIR /app<br><br># Copy the Maven project files. Use relative paths from SpringBoot-For-Beginners directory<br>COPY payment-manager/pom.xml .<br>COPY payment-manager/src ./src<br><br># Build the application. No need to run tests.<br>RUN mvn clean package -DskipTests<br><br># Use a minimal JRE image to run the app<br>FROM eclipse-temurin:21-jre-alpine<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the built JAR from the builder stage<br>COPY --from=builder /app/target/*.jar payment_manager.jar<br><br># Expose the application port<br>EXPOSE 8080<br><br># Run the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;payment_manager.jar&quot;]</pre><p>Check out the comments in the Dockerfile to see what I’ve done here. Just to be clear, this isn’t a deep dive into Docker or writing Dockerfiles.</p><p>For the first part of the demo, I’ll be setting up our H2 database. To do this, I’ll update the application.properties file. I&#39;ll set the profiles to Dev,H2Repo and enable the H2 database configs by <strong>uncommenting</strong> them. I&#39;ll also <strong>comment out the MySQL-specific configurations</strong> for now. Pretty simple, but this will get us going for this demo!</p><pre>spring.application.name=payment-manager<br><br>spring.profiles.active=Dev,H2Repo<br><br>###### Authorization related configurations ######<br>spring.security.oauth2.resourceserver.jwt.issuer-uri=https://api.asgardeo.io/t/springdemo/oauth2/token<br># Set this if the Auth server does not support OIDC discovery.<br># spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://api.asgardeo.io/t/springdemo/oauth2/jwks<br><br>######## MySQL Database related configurations ######<br>#spring.datasource.url=jdbc:mysql://localhost:3306/Payments_Db<br>#spring.datasource.username=root<br>#spring.datasource.password=root<br>## Show the sql queries in the logger.<br>#spring.jpa.show-sql=true<br>## (Optional) Format the logged queries for a more readable way.<br>## spring.jpa.properties.hibernate.format_sql=true<br>## For hibernate to generate SQL queries optimized for a Mysql database.<br>#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect<br><br>###### H2 Database related configurations ######<br># Access the h2 console from browser.<br>spring.h2.console.enabled=true<br>spring.datasource.generate-unique-name=false<br>spring.datasource.name=Payments_Db<br>spring.datasource.username=sa<br># No password is set here.<br># spring.datasource.password=sa<br><br># Add this when the script needs to execute. Usually this is done for the H2 in-memory dbs.<br>spring.sql.init.mode=always<br># Add this to init schema if the schema.sql file is not in the resources directory.<br>spring.sql.init.schema-locations=classpath:dbscripts/h2/schema.sql<br><br># Since we have added JPA, spring handles initiation differently. This is added so that initial deta insertion may<br># happen as expected.<br>spring.jpa.hibernate.ddl-auto=update</pre><p>Now, let’s change the scope of the H2 dependency to runtime in the pom.xml file.</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br> &lt;artifactId&gt;h2&lt;/artifactId&gt;<br> &lt;scope&gt;runtime&lt;/scope&gt;<br> &lt;!--&lt;scope&gt;test&lt;/scope&gt;--&gt;<br>&lt;/dependency&gt;</pre><p>Before we move on to building the image, go ahead and build the project, run it, and make sure everything is working fine. Once you’ve confirmed it’s working, navigate to the SpringBoot-For-Beginners directory and run the following command. Oh, and don’t forget to ensure that Docker is running! 🐳</p><pre>docker image build -t payment-manager-img:v0.0.1 -f payment-manager/dockerfiles/payment-manager-dockerfile .</pre><p>This command builds a Docker image using the Dockerfile that we created earlier. Let’s break it down:</p><ul><li>-t payment-manager-img:v0.0.1: The -t flag is used to tag the image as payment-manager-img. Also, I have specified a version for this image.</li><li>-f payment-manager/dockerfiles/payment-manager-dockerfile: The -f flag specifies the path to the Dockerfile. By default, Docker looks for a file named Dockerfile in the current directory. Since I have used a different location, I need to specify that path.</li><li>.: This is the build context. In this case, the current directory (.) is used as the context.</li></ul><p>Now, check the list of images using the docker image ls command, and you should see that our image has been successfully created! 🎉</p><p>Now, use the following command to start a container for our payment manager web server:</p><pre>docker run --name payment_manager -d -p 8080:8080 payment-manager-img:v0.0.1</pre><p>Now, run docker ps command to check if our container is running. This will list the running containers. We should see your container listed there, indicating that the payment manager web server is up and running inside the Docker container! 🎉</p><h4>Externally mounting a config file</h4><p>🎉 Congrats on making it this far! But hold up; our Docker image has a small issue. Right now, our server is always using the application.properties file inside the source code. That means anytime we need to tweak a config, we have to modify the file and rebuild the image. Not ideal, right? 😅</p><p>To make things more flexible, I’m gonna improve our setup so the server refers to an external config file instead. To do this, I’ve created a new Dockerfile (since I still need the original one) and made a small but powerful improvement to the last line. Let’s dive in! 🚀</p><pre># This needs to run from the project root. That is SpringBoot-For-Beginners directory<br># Use a Maven image to build the JAR. Use alpine to reduce the size of the image.<br>FROM maven:3.9.9-eclipse-temurin-21-alpine AS builder<br><br>WORKDIR /app<br><br># Copy the Maven project files. Use relative paths from SpringBoot-For-Beginners directory<br>COPY payment-manager/pom.xml .<br>COPY payment-manager/src ./src<br><br># Build the application. No need to run tests.<br>RUN mvn clean package -DskipTests<br><br># Use a minimal JRE image to run the app<br>FROM eclipse-temurin:21-jre-alpine<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the built JAR from the builder stage<br>COPY --from=builder /app/target/*.jar payment_manager.jar<br><br># Expose the application port<br>EXPOSE 8080<br><br># Run the application<br>ENTRYPOINT [&quot;java&quot;, &quot;-Dspring.config.location=file:/config/application.properties&quot;, &quot;-jar&quot;, &quot;payment_manager.jar&quot;]</pre><p>Take note of the improvement I made to the last line! (I know, I’m sorry, but I can’t dive into every detail of this change here. But hey, don’t worry. Feel free to Google it and dive deeper).</p><p>Now, let’s go ahead and create the image again using the same command as earlier. But this time, make sure to update the path to the new Dockerfile.</p><pre>docker image build -t payment-manager-img:v0.0.2 -f payment-manager/dockerfiles/external-mount/payment-manager-dockerfile .</pre><p>Notice that I’ve changed the version number to <strong>v0.0.2</strong> here.</p><p>Now, I’m going to use an external application.properties file and mount it when creating the container. This way, we don’t have to modify the file inside the image itself every time we need a change. Here&#39;s a sample command for doing that:</p><pre>docker run --name payment-manager-2 -d -p 8080:8080 -v &lt;external_path&gt;/application.properties:/config/application.properties payment-manager-img:v0.0.2</pre><p>Awesome! 🎉 Now, anytime you restart the container, it’ll refer to the specified external application.properties file. This is a much cleaner and more flexible approach, allowing you to make changes to your configuration without needing to rebuild the entire Docker image every time. 🚀</p><p>If you want, you can easily switch to a MySQL database instead of using H2 by simply updating the external application.properties file. This allows you to refer to your MySQL database without making any changes to the Docker image or application code.</p><p>That’s it from me today! I really hope you learned something valuable from this article. If you’re doing things differently or have any cool tips or tricks, I’m all ears — feel free to share in the comments! 😊</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/deploy_in_docker">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee07992adc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: Generate Spring Boot REST API stubs with Swagger]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-generate-spring-boot-rest-api-stubs-with-swagger-66c590cc7616?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c590cc7616</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 05:41:25 GMT</pubDate>
            <atom:updated>2025-03-07T05:41:25.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7uA2GnzhIGxfaaeEhHuUg.jpeg" /></figure><p>Today, I’m stepping a bit away from my usual technical deep dives to talk about something different. If you want to check out my previous articles, feel free to explore my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners?tab=readme-ov-file#articles">Git repository</a>, where I’ve been keeping track of all the code I’ve written so far.</p><p>Now, some might argue this topic isn’t exactly about Spring Boot… mmmmm, but for me, it’s just as important. It’s about <strong>documenting what you build.</strong> Let’s dive in!</p><p>API documentation should be the key to explaining how to <strong>effectively and efficiently</strong> use an API. It should provide <strong>clear instructions</strong> for someone who wants to use your API but has no clue how it was built. The harder the instructions, the higher the chance that someone might just give up on it. And honestly, what’s the point of having a great product if no one understands how to use it? 🤷‍♂</p><h4>What is OpenAPI?</h4><p>OpenAPI Specification defines a standardized format for REST APIs. It serves as a blueprint for designing, documenting, and consuming RESTful APIs in a structured and consistent way. By following this standard, APIs become more understandable, interoperable, and easier to integrate across different platforms.</p><h4>What is Swagger?</h4><p>My favorite way to document APIs is using <strong>Swagger</strong>. It’s an intuitive and powerful tool that helps create interactive API documentation. I found the best short explanation of Swagger in an <a href="https://blog.hubspot.com/website/what-is-swagger">article</a>, and here’s an extract from it:</p><blockquote>Swagger API is a set of open-source tools built to help programmers develop, design, document, and use REST APIs. The tool is built around the OpenAPI specification and contains three components: Swagger Editor, Swagger UI, and Swagger Codegen.</blockquote><p>With Swagger, you can ensure that your API documentation is complete and adheres to the OpenAPI specification, making sure everything is in line with best practices.</p><h3>Back to the tutorial…..</h3><p>My preferred approach when designing a web server is to finalize the API definitions before diving into the actual implementation. This allows me to ensure that all stakeholders are aligned and satisfied with the capabilities and user experience the server will provide.</p><p>Do you remember what we’ve done so far in my previous demos? If not, go check them out — I promise they’re pretty interesting!</p><p>So today, I’m gonna design the Payment Manager again. But this time, I’m starting with the API definition first before jumping into the implementation. Let’s goooo! 🚀</p><p>First, I’m gonna start by defining my API using <a href="https://editor.swagger.io/"><strong>Swagger Editor</strong></a>. It’s a browser-based tool that lets you write and edit API documentation easily. The best part? It has a side-by-side view, so while you’re defining the API, you can see exactly how the documentation will look to the end user. Pretty neat, right?</p><pre>openapi: 3.0.3<br>info:<br>  title: Spring Demo Payment Server - OpenAPI 3.0<br>  description: |-<br>    This is a simple set of APIs designed for a demonstration of Spring Boot. These definitions will be used to generate Spring Stubs using swagger code generator.<br>    <br>    <br>    Links:<br>    - [Medium - Sominda Gamage](https://somindagamage.medium.com/)<br>    - [Source code](https://github.com/somindatommy/SpringBoot-For-Beginners)<br>  version: 0.0.1<br>  contact:<br>    email: dummyemail@gmail.com<br><br><br>servers:<br>  - url: http://{server-url}/api/v1<br>    variables:<br>      server-url:<br>        default: &quot;localhost:8080&quot;<br><br>security:<br>  - JWTBearer: []<br>tags:<br>  - name: Payments<br>    description: Manage payment related operations<br>paths:<br>  /payments:<br>    post:<br>      tags:<br>        - Payments<br>      summary: Initiate a payment request<br>      description: Initiate a payment with another user<br>      operationId: payUser<br>      requestBody:<br>        content:<br>          application/json:<br>            schema:<br>              $ref: &#39;#/components/schemas/InitiatePaymentRequest&#39;<br>        required: true<br>      responses:<br>        &#39;200&#39;:<br>          description: Successful operation<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/PaymentInitiatorResponse&#39;<br>        &#39;400&#39;:<br>          description: Bad Request<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>        &#39;401&#39;:<br>          description: Unauthorized<br>        &#39;403&#39;:<br>          description: Forbidden<br>        &#39;500&#39;:<br>          description: Server Error<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>    get:<br>      tags:<br>        - Payments<br>      summary: Get all payments<br>      description: Get all the payments<br>      operationId: getAllPayments<br>      responses:<br>        &#39;200&#39;:<br>          description: Successful operation<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/ListPayments&#39;<br>        &#39;400&#39;:<br>          description: Bad Request<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>        &#39;401&#39;:<br>          description: Unauthorized<br>        &#39;403&#39;:<br>          description: Forbidden<br>        &#39;500&#39;:<br>          description: Server Error<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>  /payments/{payment_id}:<br>    get:<br>      tags:<br>        - Payments<br>      summary: Get payment by id<br>      description: Get payment by id<br>      operationId: getPaymentById<br>      parameters:<br>        - name: payment_id<br>          in: path<br>          description: Payment Id to retrieve.<br>          required: true<br>          schema:<br>            type: string<br>      responses:<br>        &#39;200&#39;:<br>          description: Successful operation<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Payment&#39;<br>        &#39;400&#39;:<br>          description: Bad Request<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>        &#39;401&#39;:<br>          description: Unauthorized<br>        &#39;403&#39;:<br>          description: Forbidden<br>        &#39;500&#39;:<br>          description: Server Error<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>  /payments/status/{status}:<br>    get:<br>      tags:<br>        - Payments<br>      summary: Get payments by the status<br>      description: Get all payments matching the given status<br>      operationId: getPaymentsByStatus<br>      parameters:<br>        - name: status<br>          in: path<br>          description: Status.<br>          required: true<br>          schema:<br>            type: string<br>      responses:<br>        &#39;200&#39;:<br>          description: Successful operation<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/ListPayments&#39;<br>        &#39;400&#39;:<br>          description: Bad Request<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>        &#39;401&#39;:<br>          description: Unauthorized<br>        &#39;403&#39;:<br>          description: Forbidden<br>        &#39;500&#39;:<br>          description: Server Error<br>          content:<br>            application/json:<br>              schema:<br>                $ref: &#39;#/components/schemas/Error&#39;<br>components:<br>  schemas:<br>    ListPayments:<br>      type: array<br>      items:<br>        $ref: &#39;#/components/schemas/Payment&#39;<br>    Payment:<br>      type: object<br>      description: Payment Object<br>      properties:<br>        paymentId:<br>          type: string<br>          example: &#39;PAY-20250227-204927-126871628939123-00001&#39;<br>        initiatorId:<br>          type: string<br>          example: &quot;initiator_1&quot;<br>          description: &quot;Payment initiated user&quot;<br>        receiverId:<br>          type: string<br>          example: &quot;receiver_1&quot;<br>          description: &quot;Payment receiving user&quot;<br>        amount:<br>          type: number<br>          format: double<br>          example: 100.00<br>          description: &quot;Amount to be transferred as a double&quot;<br>        status:<br>          type: string<br>          example: &quot;PENDING&quot;<br>          description: &quot;Status of the generated transaction&quot;<br>        initiatedTime:<br>          type: string<br>          format: date-time<br>          example: &#39;2025-02-27 20:49:27&#39;<br>          description: &quot;Transaction initiated time&quot;<br>      required:<br>        - paymentId<br>        - initiatorId<br>        - receiverId<br>        - amount<br>        - status<br>        - initiatedTime<br>    InitiatePaymentRequest:<br>      type: object<br>      description: This will be used to initiate a payment request<br>      required:<br>        - initiator<br>        - receiver<br>      properties:<br>        initiator:<br>          type: string<br>          example: &quot;initiator_1&quot;<br>          description: &quot;Payment initiated user&quot;<br>        receiver:<br>          type: string<br>          example: &quot;receiver_1&quot;<br>          description: &quot;Payment receiving user&quot;<br>        amount:<br>          type: number<br>          format: double<br>          example: 100.00<br>          description: &quot;Amount to be transferred as a double&quot;<br>    PaymentInitiatorResponse:<br>      type: object<br>      description: Object will be the response for initiate payment request.<br>      required:<br>        - paymentId<br>        - status<br>      properties:<br>        paymentId:<br>          type: string<br>          example: &quot;PAY-20250227-204927-126871628939123-00001&quot;<br>          description: &quot;Generated payment id&quot;<br>        status:<br>          type: string<br>          example: &quot;PENDING&quot;<br>          description: &quot;Status of the generated transaction&quot;<br>    Error:<br>      type: object<br>      properties:<br>        code:<br>          type: string<br>          example: &quot;PMS-00000&quot;<br>        message:<br>          type: string<br>          example: &quot;Some error message.&quot;<br>        description:<br>          type: string<br>          example: &quot;Some error description.&quot;<br>  securitySchemes:<br>    JWTBearer:<br>      type: http<br>      scheme: bearer<br>      bearerFormat: JWT</pre><p>I’m not gonna walk you through writing the whole API definition. Go check the docs for that! Or better yet, play around with the sample that loads when you first open Swagger Editor. It’s a great way to get a feel for how things work!</p><p>Next, I’m heading over to <strong>Spring Initializr</strong> to spin up a new project. Since I’m just focusing on implementing the REST controllers for now, I’ll only add the <strong>Spring Web</strong> dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUX8aBrUHjYF1C5EkI6qiw.png" /></figure><p>Now, go ahead and download the ZIP, extract it, and set up your project. Next, export the Swagger definition inside the resources directory. I’ve saved mine as payment-api.yaml.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*6zcycb6ZVbnznqhQJQD5ZA.png" /></figure><p>Now we need to generate the stubs. To do that, go ahead and <strong>add the following dependencies</strong> to your pom.xml. (The complete pom.xml is available in my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/swagger-integration">Git repository</a>).</p><pre>&lt;!-- Swagger api generation--&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;io.swagger.core.v3&lt;/groupId&gt;<br> &lt;artifactId&gt;swagger-annotations&lt;/artifactId&gt;<br> &lt;version&gt;2.2.28&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;jakarta.validation&lt;/groupId&gt;<br> &lt;artifactId&gt;jakarta.validation-api&lt;/artifactId&gt;<br> &lt;version&gt;3.1.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br> &lt;groupId&gt;org.openapitools&lt;/groupId&gt;<br> &lt;artifactId&gt;jackson-databind-nullable&lt;/artifactId&gt;<br> &lt;version&gt;0.2.6&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Now, head over to the build &gt; plugins section in your pom.xml file and add the following configurations:</p><pre>&lt;!--Configuration for API definitions--&gt;<br>&lt;plugin&gt;<br>&lt;groupId&gt;org.openapitools&lt;/groupId&gt;<br>&lt;artifactId&gt;openapi-generator-maven-plugin&lt;/artifactId&gt;<br>&lt;version&gt;7.12.0&lt;/version&gt;<br>&lt;executions&gt;<br> &lt;execution&gt;<br>  &lt;id&gt;generate-payment-server-apis&lt;/id&gt;<br>  &lt;goals&gt;<br>   &lt;goal&gt;generate&lt;/goal&gt;<br>  &lt;/goals&gt;<br>  &lt;configuration&gt;<br>   &lt;!--Where the yaml is located--&gt;<br>   &lt;inputSpec&gt;${project.basedir}/src/main/resources/payment-api.yaml&lt;/inputSpec&gt;<br>   &lt;!--Specifies the type of code generator to use--&gt;<br>   &lt;generatorName&gt;spring&lt;/generatorName&gt;<br>   &lt;!--Where the generated files are located--&gt;<br>   &lt;!--We can set this to &quot;.&quot; where the location will be the root--&gt;<br>   &lt;!--&lt;output&gt;${project.basedir}/generated-sources/openapi&lt;/output&gt;--&gt;<br>   &lt;!--If we use the above config, we can take the generated files outside the target. But then make sure to comment this after generating the stubs--&gt;<br>   &lt;output&gt;${project.build.directory}/generated-sources/openapi&lt;/output&gt;<br>   &lt;!--Structure from the out out directly. Notice this ends with api--&gt;<br>   &lt;apiPackage&gt;com.sominda.sample.swagger.payment_manager_swagger.api&lt;/apiPackage&gt;<br>   &lt;!--Model Structure from the out out directly. Notice this ends with model--&gt;<br>   &lt;modelPackage&gt;com.sominda.sample.swagger.payment_manager_swagger.model&lt;/modelPackage&gt;<br>   &lt;configOptions&gt;<br>    &lt;packageName&gt;com.sominda.sample.swagger.payment_manager_swagger&lt;/packageName&gt;<br>    &lt;basePackage&gt;com.sominda.sample.swagger.payment_manager_swagger&lt;/basePackage&gt;<br>    &lt;configPackage&gt;com.sominda.sample.swagger.payment_manager_swagger&lt;/configPackage&gt;<br>    &lt;dateLibrary&gt;java21&lt;/dateLibrary&gt;<br>    &lt;!--If set to false, then generate will do the controller impl and we have to extend<br>    the delegate--&gt;<br>    &lt;!--we can then implement the interface in your own service classes.--&gt;<br>    &lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt;<br>    &lt;!--When true, it generates a separate delegate class for business logic instead of implementing logic directly in the API class.--&gt;<br>    &lt;!--This has event when interfaceOnly is FALSE--&gt;<br>    &lt;delegatePattern&gt;true&lt;/delegatePattern&gt;<br>    &lt;!--When true, API methods return ResponseEntity&lt;T&gt; instead of T--&gt;<br>    &lt;useResponseEntity&gt;true&lt;/useResponseEntity&gt;<br>    &lt;useSpringBoot3&gt;true&lt;/useSpringBoot3&gt;<br>    &lt;skipOverwrite&gt;true&lt;/skipOverwrite&gt;<br>   &lt;/configOptions&gt;<br>  &lt;/configuration&gt;<br> &lt;/execution&gt;<br>&lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>This enables the OpenAPI Generator to generate stubs for us. I’ve added the basic configurations you need (with examples) to get started. If you want to dig deeper, check out the official <a href="https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin#general-configuration-parameters">documentation</a>. Now use the following command to generate the stubs.</p><pre>mvn clean generate-sources</pre><p>Now, go ahead and check the target/generated-sources/openapi directory. You’ll notice that all the model objects and API definitions have been created for you. Notice how the definitions we created have been converted into Java code. It’s pretty easy peasy! 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*LvdLy-zuqtlAodBvGGwT9A.png" /></figure><p>Again, head over to the build &gt; plugins section in your pom.xml file and add the following configurations. This will add the generated stubs to the project. Once done, just reload the pom.xml to make sure the configurations are applied correctly and everything is in effect. 🔄</p><p>This step ensures that the OpenAPI generator integrates smoothly into your build process, and you’re ready to work with the generated code.</p><pre>&lt;!--To make sure the generated code is included in the project--&gt;<br>&lt;plugin&gt;<br>&lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br>&lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;<br>&lt;version&gt;3.6.0&lt;/version&gt;<br>&lt;executions&gt;<br> &lt;execution&gt;<br>  &lt;id&gt;add-source&lt;/id&gt;<br>  &lt;phase&gt;generate-sources&lt;/phase&gt;<br>  &lt;goals&gt;<br>   &lt;goal&gt;add-source&lt;/goal&gt;<br>  &lt;/goals&gt;<br>  &lt;configuration&gt;<br>   &lt;sources&gt;<br>    &lt;source&gt;${project.build.directory}/generated-sources/openapi/src/main/java&lt;/source&gt;<br>   &lt;/sources&gt;<br>  &lt;/configuration&gt;<br> &lt;/execution&gt;<br>&lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>Notice that there is a stub PaymentsApi that contains the API definition. This is because we have added the &lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt; config. Now, we have control over the RestController implementation.</p><p>Next, we need to write a new RestController class that implements our PaymentsApi interface. This will handle the logic behind our defined API endpoints. Let&#39;s get coding! Following is the sample. Here I have only implemented a single API call just yet.</p><pre>package com.sominda.sample.swagger.payment_manager_swagger.controller;<br><br>import com.sominda.sample.swagger.payment_manager_swagger.api.PaymentsApi;<br>import com.sominda.sample.swagger.payment_manager_swagger.model.Payment;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class PaymentController implements PaymentsApi {<br><br>    @Override<br>    public ResponseEntity&lt;List&lt;Payment&gt;&gt; getAllPayments() {<br><br>        Payment payment = new Payment();<br>        payment.setPaymentId(&quot;1&quot;);<br>        List&lt;Payment&gt; payments = new ArrayList&lt;&gt;();<br>        payments.add(payment);<br>        return new ResponseEntity&lt;&gt;(payments, HttpStatus.OK);<br>    }<br>}</pre><p>Let’s break this down. 🧐 Notice the first two imports; these are the package names we configured in the OpenAPI generator (we defined different names for the models (DTOs) and APIs). Now, our PaymentController implements the PaymentsApi interface, which we talked about earlier. 🎯</p><p>In the previous controller implementation, we used @RequestMapping(&quot;/api/v1/payments&quot;). But here, we only added @RequestMapping(&quot;/api/v1&quot;). Why is that? Go ahead and check the overridden method implementation in the interface. You’ll see that the generator has already defined the method mapping according to our API definition. That’s why we only need to define the base path for the controller (/api/v1), and we don’t need to override any configurations for the getAllPayments() method. 💡</p><p>This makes our life easier and keeps the controller implementation clean!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*MqyIBDgQdK6xcsy8znFeZA.png" /></figure><p>Now, let’s go ahead and implement the rest of the methods. Please note, that these are just dummy implementations to showcase the capability, not production-ready code.</p><pre>package com.sominda.sample.swagger.payment_manager_swagger.controller;<br><br>import com.sominda.sample.swagger.payment_manager_swagger.api.PaymentsApi;<br>import com.sominda.sample.swagger.payment_manager_swagger.model.InitiatePaymentRequest;<br>import com.sominda.sample.swagger.payment_manager_swagger.model.Payment;<br>import com.sominda.sample.swagger.payment_manager_swagger.model.PaymentInitiatorResponse;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>public class PaymentController implements PaymentsApi {<br><br>    @Override<br>    public ResponseEntity&lt;List&lt;Payment&gt;&gt; getAllPayments() {<br><br>        Payment payment = new Payment();<br>        payment.setPaymentId(&quot;1&quot;);<br>        List&lt;Payment&gt; payments = new ArrayList&lt;&gt;();<br>        payments.add(payment);<br>        return new ResponseEntity&lt;&gt;(payments, HttpStatus.OK);<br>    }<br><br>    @Override<br>    public ResponseEntity&lt;Payment&gt; getPaymentById(String paymentId) {<br><br>        Payment payment = new Payment();<br>        payment.setPaymentId(&quot;12&quot;);<br>        return new ResponseEntity&lt;&gt;(payment, HttpStatus.OK);<br>    }<br><br>    @Override<br>    public ResponseEntity&lt;List&lt;Payment&gt;&gt; getPaymentsByStatus(String status) {<br><br>        return getAllPayments();<br>    }<br><br>    @Override<br>    public ResponseEntity&lt;PaymentInitiatorResponse&gt; payUser(InitiatePaymentRequest initiatePaymentRequest) {<br><br>        // Logic to initiate the payment (mocked here for simplicity)<br>        PaymentInitiatorResponse response = new PaymentInitiatorResponse();<br><br>        // For example purposes, let&#39;s assume paymentId is generated and status is &quot;PENDING&quot;<br>        String paymentId = &quot;PAY-&quot; + System.currentTimeMillis();<br>        response.setPaymentId(paymentId);<br>        response.setStatus(&quot;PENDING&quot;);<br><br>        // You can replace the above logic with your actual payment initiation logic.<br><br>        // Returning the successful response with HTTP status 200<br>        return new ResponseEntity&lt;&gt;(response, HttpStatus.OK);<br>    }<br>}</pre><p>Now, if you want to implement Authentication and Other Services, you can just copy the class from my previous implementation which I’m not gonna do now.</p><p>Let’s try the implementation and make sure this is working, yeah? One of the coolest things is that since we already have the API definitions ready, we can directly import them into Postman. If we’ve written the definition properly, Postman will automatically create a collection with all the environment variables and other configurations for us. Pretty neat, huh? 😎</p><p>This makes it super easy to share our API definition with anyone. Plus, we can even host the definition for easy access, allowing others to import it and test the API on their end without having to go through the setup process. It streamlines collaboration and ensures everyone is aligned on how the API should behave.</p><p>Go ahead and restart the server and give it a go. You’ll see that the new implementation is working as expected. The best part? It’s properly documented now! 🎉 By combining the power of Swagger and the OpenAPI Generator, we’ve not only implemented the API but also ensured it’s well-documented from the get-go, making it easy to use and maintain.</p><p>That’s it from me today! I really hope you learned something valuable from this article. If you’re doing things differently or have any cool tips or tricks, I’m all ears — feel free to share in the comments! 😊</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/swagger-integration">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c590cc7616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: Securing the APIs with tokens]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-securing-the-apis-with-tokens-586d3c13700d?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/586d3c13700d</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 17:43:13 GMT</pubDate>
            <atom:updated>2025-03-03T17:43:13.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4OsDs0BstbcV64SLSV_zQ.jpeg" /></figure><p>In the <a href="https://medium.com/@somindagamage/spring-boot-for-beginners-handling-exceptions-82efad3061cd">last article</a>, I implemented exception handling on a global scale. Now, I’d say we have a pretty decent web server (still some things left to tackle, like input validation, but we’re getting there). But here’s the thing; we can’t expose this to the outside world just yet. Why? Damn it, we didn’t properly secure the APIs! Darn it. Let’s fix that and see how we can lock things down properly.</p><p>Before we dive into the implementation, let me share my grand plan for this server. When I first thought about this design, I wanted it to be a <strong>resource server</strong>. What’s a resource server, you ask? Well, to understand that, you need a quick crash course on OAuth2.</p><p>But don’t worry, I got you covered! I’ve already written a <a href="https://medium.com/@somindagamage/oauth-2-0-for-dummies-8807cff5c3b2">blog on OAuth2</a>, so go check it out. It explains everything you need to know in a fun way. (Hey, I always try to sneak in some humor to make the tricky stuff easier to grasp! 😆).</p><p>Just a quick recap; OAuth is all about <strong>Delegated Access Control</strong>. Simply put, it means you can let another party access your resources on your behalf, but with some restrictions (because, you know, security and all that). The flow involves four key players:</p><ul><li><strong>Resource Owner</strong> (That’s you!)</li><li><strong>Authorization Server</strong> (Handles authentication &amp; token issuance)</li><li><strong>Client</strong> (The app trying to access the resource)</li><li><strong>Resource Server</strong> (That’s us!)</li></ul><p>Here’s how it works:</p><ol><li>The user accesses the <strong>client</strong> to request a resource.</li><li>The client redirects the user to the <strong>authorization server</strong> for authentication and grabs a token.</li><li>The client then presents that token to the <strong>resource server</strong> (us) when requesting the resource.</li><li>The resource server validates the token with the <strong>authorization server</strong> and, if all checks out, grants access. ✅</li></ol><p>Now that we’ve got the background sorted, let’s see how we can actually do this in <strong>Spring Boot</strong>. The good news? <strong>Spring Security</strong> makes this super easy! Specifically, we’ll be using <strong>spring-security-oauth2-resource-server</strong>. With this, you can validate credentials in two ways:</p><ul><li>Using <strong>username and password</strong> authentication.</li><li>Using <strong>tokens</strong> — and that’s what we’re prioritizing today! 🎯</li></ul><p>To add this to the project, just include the following dependency in your <strong>pom.xml</strong> (I used <strong>Spring Initializr</strong> to grab the correct one).</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-oauth2-resource-server&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Once you’ve added this, go ahead and reload the <strong>pom.xml</strong>. After that, restart the server and try making any API request. You’ll notice that all the requests are failing with an <strong>HTTP 401 Unauthorized</strong> error. Now, try hitting any <strong>GET request</strong> (e.g., http://localhost:8080/api/v1/payments) in the browser. You’ll see that you’re being redirected to the out-of-the-box (OOTB) login page, asking for your credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Nh4f0wcaat1aqDVbzW2sPQ.png" /></figure><p>What the hell just happened? 😱 Well, once the dependency is added, Spring automatically secures all the available endpoints. The guy is <em>really</em> firm on keeping things safe! But don’t worry, to fix this (Since we do not want username and password-based authentication), just add exclude = {SecurityAutoConfiguration.class} to the PaymentManagerApplication class.</p><pre>@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})<br>public class PaymentManagerApplication {<br><br>    public static void main(String[] args) {<br><br>        SpringApplication.run(PaymentManagerApplication.class, args);<br>    }<br>}</pre><p>SecurityAutoConfiguration class is the auto-configuration class responsible for setting up Spring Security when it’s on the classpath. By excluding it, we tell Spring not to automatically configure authentication and security-related features.</p><p>If you want to dive deep into OAuth 2.0 Resource Server JWT, check out the <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html">Spring documentation</a>. It covers the architecture and everything you need to know. Today, though, I’ll explain the majority of it in a simple way. Well, at least I’ll try my best! 😅</p><p>For this demo, I’m using <a href="https://wso2.com/asgardeo/"><strong>WSO2 Asgardeo</strong></a> as the Authorization Server (Because, well… I’ve worked on the Asgardeo team and know this thing inside and out! 😎). Of course, you can use any IAM provider you prefer and the only difference will be in the configurations.</p><p>Before we dive in, here’s what I’ve set up in <strong>Asgardeo</strong> as prerequisites:</p><p>1️⃣ <strong>Created an organization</strong> and added an application as my client.<br>2️⃣ <strong>Set up two roles:</strong></p><ul><li><strong>Cashier</strong> — Can initiate payments and retrieve a payment by ID.</li><li><strong>Manager</strong> — Can only view payments.</li></ul><p>3️⃣ <strong>Added three users:</strong></p><ul><li>cashier01@mnmc.com → Has only the <strong>Cashier</strong> role.</li><li>manager01@mnmc.com → Has only the <strong>Manager</strong> role.</li><li>admin01@mnmc.com → Has <strong>both</strong> roles.</li></ul><p>After setting this up, In the application configurations section, I found the <strong>issuer</strong> for my application is:</p><pre>https://api.asgardeo.io/t/springdemo/oauth2/token</pre><h3>Securing with JWTs</h3><p>Let’s kick things off by configuring it in the <strong>application.properties</strong>. First, we need to specify <strong>which</strong> authorization server to use. No magic here; just a simple config tweak!</p><pre>spring.security.oauth2.resourceserver.jwt.issuer-uri=https://api.asgardeo.io/t/springdemo/oauth2/token</pre><p>Once this is configured, the server will automatically call the <strong>discovery endpoint</strong> of the authorization server and fetch the <strong>JSON Web Key Set (JWKS)</strong> from the JWKS endpoint. But here’s the catch; if the authorization server <strong>doesn’t</strong> support OIDC discovery, we’ll have to manually set the JWKS endpoint to fetch the keys directly. No big deal, just an extra step! 😃</p><pre>spring.security.oauth2.resourceserver.jwt.issuer-uri=https://api.asgardeo.io/t/springdemo/oauth2/token<br>spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://api.asgardeo.io/t/springdemo/oauth2/jwks</pre><p>Once these are set, when a request arrives, our server will:</p><ul><li><strong>Validate the signature</strong> to ensure the token hasn’t been tampered with.</li><li><strong>Check the JWT’s </strong><strong>exp (expiration) and </strong><strong>nbf (not before) timestamps</strong> to make sure it’s still valid.</li><li><strong>Verify the </strong><strong>iss (issuer) claim</strong> to confirm the token is from the right authorization server.</li></ul><p><strong>NOTE:</strong> If you also need to validate the <strong>audiences</strong>, you can easily do that via configurations. No extra coding hassle!</p><p>When you run the application now, you will see errors.</p><pre>Description:<br>Parameter 0 of method jwtSecurityFilterChain in org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerJwtConfiguration$OAuth2SecurityFilterChainConfiguration required a bean of type &#39;org.springframework.security.config.annotation.web.builders.HttpSecurity&#39; that could not be found.<br><br>Action:<br>Consider defining a bean of type &#39;org.springframework.security.config.annotation.web.builders.HttpSecurity&#39; in your configuration.<br><br>Process finished with exit code 1</pre><p>So, the error basically tells us what to do. Let’s define our own solution! First up, I’m going to introduce a new profile. The idea here is to <strong>bypass all authentication during Dev mode</strong>. Come on, who wants to get a new token every time they make a change? Not me! 😅</p><pre>package com.sominda.sample.payment_manager.security;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br><br>@Profile(&quot;Dev&quot;)<br>@Configuration<br>@EnableWebSecurity<br>public class DevSecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br><br>        http.authorizeHttpRequests(authr -&gt; {<br>            authr.anyRequest().permitAll();<br>        });<br>        return http.build();<br>    }<br>}</pre><p>So, here I’ve introduced a new <strong>profile</strong> to achieve the first requirement.</p><p>The @Configuration annotation is used to mark a class as a source of bean definitions. (Quick note: <strong>Beans</strong> are objects that make up a Spring Boot application, but that’s a whole topic for another day! 😅)</p><p>The @EnableWebSecurity annotation is used to enable <strong>Spring Security</strong> custom configurations. It&#39;s like flipping the switch to activate security in our app. 🔒</p><p>The @Bean annotation tells Spring that this method is defining a Spring bean. In this case, the return value (SecurityFilterChain) will be treated as a bean and registered in the application context. Notice the method name and return type.</p><p>The SecurityFilterChain beans are the ones that intercept incoming requests and apply security filters. This is where I’m customizing the <strong>authorization flow</strong>.</p><p>The HttpSecurity object is key for configuring HTTP-based security settings. Using its methods, we can define things like <strong>authorization rules</strong>, <strong>authentication mechanisms</strong>, and more.</p><p>The authorizeHttpRequests() method is used to define how HTTP requests should be authorized. It takes a lambda expression (authr -&gt; {…}), where authr is an instance of HttpSecurity.AuthorizeRequestsConfigurer. This gives us the flexibility to configure specific HTTP request authorization rules. In this case, I’m saying, “Hey, allow <strong>any</strong> HTTP request without needing authentication” with;</p><pre>authr.anyRequest().permitAll();</pre><p>Update the <strong>application.properties </strong>file with the new profile settings.</p><pre>spring.profiles.active=Dev,MySQLRepo</pre><p>Now, let’s restart the server and notice that we can access any API without authentication. This is great for development (easy testing, right?), but definitely not something we want in production.</p><p>So, let’s implement <strong>role-based authorization</strong>. Here’s what I have in mind:</p><ul><li><strong>Role: Cashier — </strong>Can <strong>GET</strong> a payment by ID and <strong>POST</strong> a payment.</li><li><strong>Role: Manager</strong> — Can <strong>GET</strong> all payments.</li><li><strong>Open Endpoint:</strong> I want to keep getPaymentsByStatus open for demonstration purposes, so no role validation there.</li></ul><p>Let’s make this happen! I’m going to introduce a new profile called <strong>JWT</strong> along with a brand new config class to keep things organized.</p><pre>package com.sominda.sample.payment_manager.security;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.http.HttpMethod;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br><br>@Profile(&quot;JWT&quot;)<br>@Configuration<br>@EnableWebSecurity<br>public class JWTSecurityConfig {<br><br>    private final String MANAGER_ROLE = &quot;Manager&quot;;<br>    private final String CASHIER_ROLE = &quot;Cashier&quot;;<br><br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br><br>        http.authorizeHttpRequests(authr -&gt; authr<br>                .requestMatchers(HttpMethod.GET, &quot;/api/v1/payments/status/*&quot;).permitAll()<br>                .requestMatchers(HttpMethod.GET, &quot;/api/v1/payments&quot;).hasAuthority(MANAGER_ROLE)<br>                .requestMatchers(HttpMethod.GET, &quot;/api/v1/payments/*&quot;).hasAuthority(CASHIER_ROLE)<br>                .requestMatchers(HttpMethod.POST, &quot;/api/v1/payments&quot;).hasAuthority(CASHIER_ROLE)<br>                .anyRequest().authenticated()<br>                  )<br>          .oauth2ResourceServer(oauth2 -&gt; oauth2.jwt(Customizer.withDefaults()));<br>        return http.build();<br>    }<br>}</pre><p>The only thing different from the previous implementation is what’s inside the securityFilterChain() method. I’ve used a <strong>request matching approach</strong> to support my use case. Honestly, I don’t think I need to dive into the details of this. But just a heads-up, the <strong>order</strong> in which you define these matters, as Spring processes them one by one.</p><p>The oauth2ResourceServer() method sets up our application as an <strong>OAuth2 resource server</strong>. Inside that, the oauth2 -&gt; oauth2.jwt(...) part specifies that our resource server should use <strong>JWT</strong> as the authentication mechanism. Customizer.withDefaults() is just a handy utility method that provides a default configuration for JWT authentication. The next new line here is,</p><pre>.anyRequest().authenticated();</pre><p>which ensures that <strong>all other endpoints</strong> need authentication. Simple, right?</p><p>Now, let’s update the profile configuration and restart the server. Try making any API request (except for the status request). You’ll notice that all the requests are failing with an <strong>HTTP 403 Forbidden</strong> error. Now, try <strong>GET</strong> api/v1/payments/status/SUCCESS, and you should see a <strong>success</strong> response! This means our custom authorization is working perfectly. 🎉</p><p>Next up: we just need to make sure the requests are sent with <strong>valid tokens</strong>. Let’s do that! 🔑</p><p>If you’re using <strong>Postman</strong>, you can easily set the <strong>Auth type</strong> to <strong>Bearer</strong>. Just head over to the <strong>Authorization</strong> tab (or you can set it at the collection level and configure it to inherit from the parent). That way, you don’t have to set it manually for every single request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dhfIJx4BdGhpFoT_0wLHw.png" /></figure><p>So, I got a token from the <strong>manager user</strong> and tried fetching all payments. If this worked for you, congrats! 🎉 But, for me, it didn’t work and threw the same error.</p><p>This is where I can introduce you to a new lesson. When I decoded the token, it looked like this, and if you look closely, you’ll notice how the <strong>roles</strong> are included in the payload.</p><pre>{<br>  &quot;isk&quot;:&quot;98cb7fcb8105de1edd01186a324f42120081237635c67733b8…&quot;<br>  &quot;at_hash&quot;:&quot;UiG9_PYYa98M4DGaQ7H7pQ&quot;<br>  &quot;sub&quot;:&quot;df3fd287-a5d3-48d3-b33f-8456299b9149&quot;<br>  &quot;amr&quot;:[<br>    0:&quot;BasicAuthenticator&quot;<br>  ]<br>  &quot;roles&quot;:[<br>    0:&quot;Manager&quot;<br>    1:&quot;everyone&quot;<br>  ]<br>  &quot;iss&quot;:&quot;https://api.asgardeo.io/t/springdemo/oauth2/token&quot;<br>  &quot;given_name&quot;:&quot;ManagerFirst&quot;<br>  &quot;sid&quot;:&quot;efc55117-dfa3-4816-b525-2c234c98cad9&quot;<br>  &quot;aud&quot;:&quot;9JMMFbhFx2mc0PfwXAoTf8LmODYa&quot;<br>  &quot;c_hash&quot;:&quot;Pb2HOeUoq1eV7qketFy8Rw&quot;<br>  &quot;nbf&quot;:1740974629<br>  &quot;azp&quot;:&quot;9JMMFbhFx2mc0PfwXAoTf8LmODYa&quot;<br>  &quot;org_id&quot;:&quot;3257e7ac-bc7e-4e30-9471-5d68de7a16a2&quot;<br>  &quot;exp&quot;:1741060629<br>  &quot;org_name&quot;:&quot;springdemo&quot;<br>  &quot;iat&quot;:1740974629<br>  &quot;jti&quot;:&quot;31fffea5-fdde-4988-b0ae-cedad7368884&quot;<br>  &quot;email&quot;:&quot;manager01@mnmc.com&quot;<br>  &quot;username&quot;:&quot;manager01@mnmc.com&quot;<br>}</pre><p>By default, Spring Security looks for the scope claim or authorities<strong> </strong>claim in the JWT. But in my case, the <strong>roles</strong> are coming in as roles<strong> </strong>instead. To fix this, I’m introducing the following method.</p><pre>@Bean<br>public JwtAuthenticationConverter jwtAuthenticationConverter() {<br><br>    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();<br>    grantedAuthoritiesConverter.setAuthoritiesClaimName(&quot;roles&quot;);<br><br>    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();<br>    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -&gt; {<br>        Collection&lt;GrantedAuthority&gt; authorities = grantedAuthoritiesConverter.convert(jwt);<br>        Logger logger = LoggerFactory.getLogger(JwtAuthenticationConverter.class);<br>        logger.info(&quot;Extracted Authorities: {}&quot;, authorities);<br>        return authorities;<br>    });<br><br>    return jwtAuthenticationConverter;<br>}</pre><p>Let’s break this down.</p><p>The JwtAuthenticationConverter is responsible for converting a JWT into an <strong>Authentication object</strong> in Spring Security. This object is used to authorize and authenticate the user.</p><p>I’ve configured it to use roles as the <strong>authorities claim</strong> (which I mentioned earlier). Next, I set up the JwtAuthenticationConverter to use the JwtGrantedAuthoritiesConverter to convert the JWT into a collection of GrantedAuthority objects. These objects represent the user’s <strong>roles</strong> or <strong>authorities</strong>.</p><p>Inside the lambda function, I’m just logging the extracted authorities to make sure my fix is working. You won’t need this step in the future as it’s just for debugging.</p><p>Now, restart the server and try the same API again. Guess what? <strong>It failed again.</strong> 😅 But, when I checked the logs, I noticed the following log that we had added earlier.</p><pre>Extracted Authorities: [SCOPE_Manager, SCOPE_everyone]</pre><p>And that, my friends, brings us to our next lesson! By default, Spring expects role names to start with <strong>SCOPE_</strong> (because why not add extra work for us, right? 😆). There are two ways to fix this:</p><ul><li>Rename the roles to include the <strong>SCOPE_</strong> prefix.</li><li>Tell Spring to chill and stop expecting that prefix.</li></ul><p>I’m going with option 2 because, honestly, who wants to rename everything? So, I made a tiny but mighty improvement to our jwtAuthenticationConverter() method; just drop that unnecessary SCOPE_ prefix by setting it to an empty string. Here’s the fully updated method in all its glory:</p><pre>@Bean<br>public JwtAuthenticationConverter jwtAuthenticationConverter() {<br><br>    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();<br>    // Need to set the authorize claim name if we are moving away from the default scope or authorities claims.<br>    grantedAuthoritiesConverter.setAuthoritiesClaimName(&quot;roles&quot;);<br>    // Get rid of any prefix expectations. Eg: SCOPE_Manager.<br>    grantedAuthoritiesConverter.setAuthorityPrefix(&quot;&quot;);<br><br>    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();<br>    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -&gt; {<br>        Collection&lt;GrantedAuthority&gt; authorities = grantedAuthoritiesConverter.convert(jwt);<br>        Logger logger = LoggerFactory.getLogger(JwtAuthenticationConverter.class);<br>        logger.info(&quot;Extracted Authorities: {}&quot;, authorities);<br>        return authorities;<br>    });<br><br>    return jwtAuthenticationConverter;<br>}</pre><p>Now, let’s restart the server and see if this finally does the trick! Try hitting the same API again and take a peek at the logs. 👀</p><pre>Extracted Authorities: [Manager, everyone]</pre><p>The prefix issue is <strong>gone</strong> just like that! Now, our roles are mapped correctly, and everything should work as expected.</p><p>Go ahead and try the following:</p><p>👉 <strong>GET</strong> http://localhost:8080/api/v1/payments/&lt;Id&gt; and <strong>POST</strong> a new payment using a <strong>manager</strong> token. 🚫 Notice that the manager user gets <strong>denied</strong> access.</p><p>👉 Now, switch to a <strong>cashier</strong> token and retry the same APIs. ✅ This time, it should work as expected!</p><p>👉 Finally, try with an <strong>admin</strong> token. 🔥 You’ll notice that the admin user can access <strong>all</strong> the APIs without any restrictions.</p><p>This means our <strong>Role-Based Access Control (RBAC)</strong> is working perfectly!</p><p>Haha, yeah, that was a ride! 🎢 Give yourself a well-deserved pat on the back! But hey, before we call it a day, let’s try <strong>one last small thing</strong>. Ready? Let’s go!</p><h4>Getting Authenticated User’s Details</h4><p>Exactly! Now that we’ve successfully authenticated users, we can access their details inside our application. 🔐</p><p>Spring Security stores the authentication details in SecurityContextHolder, we can easily retrieve them. Let’s do a <strong>quick print</strong> to see what’s available. I’ve made a few changes to the PaymentController<strong>.</strong></p><pre>@GetMapping(&quot;/authdata&quot;)<br>@ResponseStatus(HttpStatus.OK)<br>public void getAuthentication() {<br><br>    // Print authenticated user details.<br>    printAuthenticatedUser();<br>}<br><br>private void printAuthenticatedUser() {<br><br>    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();<br>    if (authentication == null) {<br>        throw new PaymentManagerServerException(&quot;02&quot;, &quot;Unable to find authentication data&quot;, &quot;Server failed to &quot; +<br>                &quot;find user information for the authenticated user&quot;);<br>    }<br>    Object principal = authentication.getPrincipal();<br>    if (principal == null) {<br>        throw new PaymentManagerServerException(&quot;03&quot;, &quot;Unable to find authenticated principal&quot;, &quot;Server &quot; +<br>                &quot;failed to find user information for the authenticated user&quot;);<br>    }<br>    // Since this is a JWT, we can map it to jwt object type.<br>    Map&lt;String, Object&gt; claims = ((Jwt) principal).getClaims();<br>    if (CollectionUtils.isEmpty(claims)) {<br>        throw new PaymentManagerServerException(&quot;04&quot;, &quot;Unable to authenticated user claims&quot;, &quot;Server obtain &quot; +<br>                &quot;authenticated user claims&quot;);<br>    }<br>    System.out.printf(&quot;Authenticated user: %s, %s, %s, %s%n&quot;, claims.get(&quot;sid&quot;),claims.get(<br>            &quot;username&quot;), claims.get(&quot;given_name&quot;),claims.get(&quot;email&quot;));<br>}</pre><p>The principal object contains the actual user information. Since we’re using a JWT, we can easily cast it into a Jwt object and retrieve the claims. To showcase this, I’ve introduced a new endpoint, as I have some exciting plans for this demo moving forward. Feel free to use this approach based on your own needs. Just remember to update the JWTSecurityConfig with the new authorization rule.</p><pre>.requestMatchers(HttpMethod.GET, &quot;/api/v1/payments/authdata&quot;).authenticated()</pre><p>Now, let’s restart the server and make a <strong>GET</strong> request to api/v1/payments/authdata with any valid token. Check out the logs and you’ll see the user details and roles we printed earlier!</p><pre>Authenticated user: e7ae7c50-c715-4120-bc00-6e2c07bf6d3a, manager01@mnmc.com, ManagerFirst, manager01@mnmc.com</pre><p>Phew, that’s how we do this! 😅 God, this was a long article! So, let’s call it a day for now. I’ll be diving into how to work with <strong>opaque tokens</strong> in a future article. Stay tuned! 😎</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/secure-api-jwt">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586d3c13700d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: Handling exceptions]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-handling-exceptions-82efad3061cd?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/82efad3061cd</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 23:42:10 GMT</pubDate>
            <atom:updated>2025-03-01T23:42:10.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MD691dxuuBsyb2HdQwg1g.png" /></figure><p>In my <a href="https://medium.com/@somindagamage/spring-boot-for-beginners-adding-a-database-layer-part-2-with-jpa-and-hibernate-03f6fd0cb238">last article</a>, we built a fine-looking server that happily chats with a MySQL database. But let’s be real. The databases have a knack for throwing tantrums now and then. Integrity violations, constraint issues, or just plain bad luck, something’s bound to go wrong.</p><p>Now, here’s a fun little detail. Have you noticed that we haven’t handled any exceptions yet? Yep, our server is currently just hoping for the best. Let’s fix that before it inevitably blows up in our faces.</p><p>With Spring Boot, there are plenty of ways to gracefully handle exceptions. If you’re feeling adventurous, there are tons of blogs out there covering different approaches (like <a href="https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc">this one</a> I found online).</p><p>But today, I’m going to show you my favorite; using @ControllerAdvice for global exception handling. Because let’s be honest, who wants to write the same try-catch blocks over and over again? Ain’t nobody got time for that!</p><p>First things first. I need to define the information I want to show the user as JSON. And for that, I’m going to create a model class.</p><pre>package com.sominda.sample.payment_manager.model.api;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br><br>@Getter<br>@AllArgsConstructor<br>public class ErrorResponse {<br><br>    private String code;<br>    private String message;<br>    private String description;<br>}</pre><p>As a personal practice, I love creating a family of exceptions. It’s like having a well-organized family tree and it helps me handle exceptions much more efficiently. Here’s how I implement it. Make sure to pay attention to the comments along the way, as they’ll guide you through the hierarchy of exceptions. Think of it like a treasure map for your exception handling!</p><pre>package com.sominda.sample.payment_manager.exception;<br><br>import lombok.Getter;<br><br>/**<br> * This will be the parent type of all the exceptions thrown from the service.<br> */<br>@Getter<br>public class PaymentManagerException extends RuntimeException {<br><br>    private final String code;<br>    private final String description;<br><br>    public PaymentManagerException(String code, String message, String description) {<br><br>        super(message);<br>        this.code = code;<br>        this.description = description;<br>    }<br><br>    public PaymentManagerException(String code, String message, Throwable cause) {<br><br>        super(message, cause);<br>        this.code = code;<br>        this.description = message;<br>    }<br>}</pre><pre>package com.sominda.sample.payment_manager.exception;<br><br>/**<br> * Thrown for client errors.<br> */<br>public class PaymentManagerClientException extends PaymentManagerException {<br><br>    public PaymentManagerClientException(String code, String message, String description) {<br><br>        super(code, message, description);<br>    }<br><br>    public PaymentManagerClientException(String code, String message, Throwable cause) {<br><br>        super(code, message, cause);<br>    }<br><br>    @Override<br>    public String getCode() {<br><br>        // Append a prefix to indicate this is a client exception starting with 140xxx.<br>        // PME stands for payment manager exception.<br>        return &quot;PME-140&quot; + super.getCode();<br>    }<br>}</pre><pre>package com.sominda.sample.payment_manager.exception;<br><br>/**<br> * Thrown for internal server error which were unexpected.<br> */<br>public class PaymentManagerServerException extends PaymentManagerException{<br><br>    public PaymentManagerServerException(String code, String message, String description) {<br><br>        super(code, message, description);<br>    }<br><br>    public PaymentManagerServerException(String code, String message, Throwable cause) {<br><br>        super(code, message, cause);<br>    }<br><br>    @Override<br>    public String getCode() {<br><br>        // Append a prefix to indicate this is a client exception starting with 500xxx.<br>        // PME stands for payment manager exception.<br>        return &quot;PME-500&quot; + super.getCode();<br>    }<br>}</pre><p>Notice that the parent exception class, PaymentManagerException extending RuntimeException. Now, this comes with a few perks (and yes, a couple of downsides too).</p><ul><li>RuntimeException is an unchecked exception, meaning you don’t need to explicitly declare it in a method&#39;s throws clause. So its developers don’t need to add throws declarations to every method in the call stack.</li><li>Extending from RuntimeException makes it easier for Spring’s global exception handling (thanks to @ControllerAdvice) to work its magic and manage the exception.</li></ul><h4>What is Global Exception Handling?</h4><p>Alright, now we’re talking about handling exceptions across the entire application. Enter @ControllerAdvice—think of it as an annotation-driven interceptor that swoops in and handles those pesky exceptions for you. Let’s dive into how this works in action.</p><pre>package com.sominda.sample.payment_manager.exception;<br><br>import com.sominda.sample.payment_manager.model.api.ErrorResponse;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.ControllerAdvice;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br><br>@ControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(PaymentManagerClientException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleClientExceptions(PaymentManagerClientException ex) {<br><br>        ErrorResponse error = new ErrorResponse(ex.getCode(), ex.getMessage(), ex.getDescription());<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.BAD_REQUEST);<br>    }<br><br>    @ExceptionHandler(PaymentManagerServerException.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleServerExceptions(PaymentManagerServerException ex) {<br><br>        ErrorResponse error = new ErrorResponse(ex.getCode(), ex.getMessage(), ex.getDescription());<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br><br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ErrorResponse&gt; handleGeneralExceptions(Exception ex) {<br><br>        System.out.println(&quot;UNEXPECTED EXCEPTION: &quot; + ex.getMessage());<br>        ex.printStackTrace();<br>        ErrorResponse error = new ErrorResponse(&quot;PME-50000&quot;, &quot;Internal Server Error&quot;, ex.getMessage());<br>        return new ResponseEntity&lt;&gt;(error, HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br>}</pre><p>I think this is a pretty straightforward implementation. Here’s how I’ve set it up:</p><ul><li><strong>handleClientExceptions</strong>: This one handles client-side errors with PaymentManagerClientException.</li><li><strong>handleServerExceptions</strong>: This method takes care of server-side errors using PaymentManagerServerException.</li><li><strong>handleGeneralExceptions</strong>: This is the catch-all for any general exceptions that extend the Exception class.</li></ul><p>Now, here’s the magic. The @ExceptionHandler annotation. It’s used to define methods that handle exceptions thrown by controller methods. The cool thing is, the method annotated with @ExceptionHandler can return pretty much any response type supported by Spring (like ResponseEntity, String, ModelAndView, etc.).</p><p>When you specify a specific exception type, that method will only catch and handle that type of exception (and its subclasses). Since I have multiple @ExceptionHandler methods, <strong>Spring will first try to match the most specific exception. If that doesn’t match, it’ll move on to handle the more general exceptions.</strong> It’s like Spring’s way of making sure nothing slips through the cracks. This approach makes our lives so much easier!</p><p>To keep things simple and demonstrate this, I’ve added a little verification step in the SQLRepository implementation. Nothing too fancy, just a quick check to show how everything comes together in a real-world scenario.</p><pre>@Override<br>public Payment getPaymentById(String paymentId) {<br><br>    System.out.println(&quot;Fetching a payment from id SQLRepository&quot;);<br>    return paymentsJPARepository.findById(paymentId)<br>            .orElseThrow(() -&gt; new PaymentManagerClientException(&quot;01&quot;, &quot;No payment found&quot;, &quot;No payment found &quot; +<br>                    &quot;with the given id: &quot; + paymentId));<br>}</pre><p>Now, go ahead and restart the server. After that, try sending an invalid ID to the GET /api/v1/payments/&lt;invalid_id&gt; API. You should see a nice, informative response from the server. Notice that we’ve received an <strong>HTTP 400 status code</strong> with the following response. Looks like our server is being very specific about the error, just the way we like it!</p><pre>{<br>  &quot;code&quot;: &quot;PME-14001&quot;,<br>  &quot;message&quot;: &quot;No payment found&quot;,<br>  &quot;description&quot;: &quot;No payment found with the given id: PAY-20250301-103929-126871628939123-00002&quot;<br>}</pre><p>Now, let’s see how unexpected exceptions are handled. Try sending an invalid state with the GET /api/v1/payments/status/&lt;invalid_state&gt; API. You should notice that we’ve received an <strong>HTTP 500</strong> status code, along with the following response.</p><pre>{<br>  &quot;code&quot;: &quot;PME-50000&quot;,<br>  &quot;message&quot;: &quot;Internal Server Error&quot;,<br>  &quot;description&quot;: &quot;No enum constant com.sominda.sample.payment_manager.model.Status.INVALID_STATE&quot;<br>}</pre><p>This is the expected response, right? Now, let’s take a peek at the console logs to see what’s going on behind the scenes.</p><pre>UNEXPECTED EXCEPTION: No enum constant com.sominda.sample.payment_manager.model.Status.INVALID_STATE<br>java.lang.IllegalArgumentException: No enum constant com.sominda.sample.payment_manager.model.Status.INVALID_STATE<br> at java.base/java.lang.Enum.valueOf(Enum.java:293)<br> at com.sominda.sample.payment_manager.model.Status.valueOf(Status.java:3)<br> at com.sominda.sample.payment_manager.service.PaymentManagerService.getPaymentsByStatus(PaymentManagerService.java:34)<br> at com.sominda.sample.payment_manager.controller.PaymentController.getPaymentsByStatus(PaymentController.java:54)<br> at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)<br> at java.base/java.lang.reflect.Method.invoke(Method.java:580)<br>......<br>......</pre><p>Oops! I missed handling validation for the enum type. But no worries, since we’ve got global exception handling in place, the handleGeneralExceptions handler stepped up and saved the day. Thanks to that, the client won’t see any inconsistencies with the server&#39;s behavior. Crisis averted!</p><p>And that’s it! That’s how we can do some quick firefighting with exception handling. When things go wrong, global exception handling swoops in to save the day and keep everything running smoothly. 😎</p><p>I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/exception-handling">git repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82efad3061cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: Adding a database layer (Part 2) : With JPA and Hibernate]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-adding-a-database-layer-part-2-with-jpa-and-hibernate-03f6fd0cb238?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f6fd0cb238</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 17:35:54 GMT</pubDate>
            <atom:updated>2025-03-01T23:37:43.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot for Beginners: Adding a database layer (Part 2) : With JPA and Hibernate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02lOS6HdJNd543x-ksW7FQ.jpeg" /></figure><p>Interacting with data using <strong>Spring Boot</strong> is a topic that could go on for days. What I’m covering today? Just the <strong>tip of the iceberg</strong>.</p><p>If you’re looking for an in-depth deep dive into JPA, well… you’re in the wrong place. But if you just need a little push to get started, my friend, you’re more than welcome here!</p><p>In my <a href="https://somindagamage.medium.com/spring-boot-for-beginners-adding-a-database-layer-part-1-fef164ec0edd">last blog</a>, I mentioned a way you can talk to databases. This time, we’re stepping things up a bit with <strong>JPA </strong>and<strong> Hibernate</strong>.</p><h3>What is JPA?</h3><p>JPA (<strong>Java Persistence API</strong>) is a <strong>specification</strong> that defines a standard way to interact with relational databases using Java objects. Instead of writing raw SQL queries, JPA allows you to work with Java objects (entities) while the underlying database interactions are handled for you. However, JPA itself doesn’t actually do the work, it’s just a guideline. To use it, we rely on JPA providers like <strong>Hibernate, OpenJPA</strong>, and<strong> EclipseLink</strong>, which implement the spec and do the heavy lifting behind the scenes.</p><h3>What about Hibernate?</h3><p>Hibernate is <strong>one of the most popular JPA implementations</strong>, and it takes care of mapping Java objects to database tables. With Hibernate, you can perform CRUD operations without writing tons of boilerplate SQL. It also brings some cool features like automatic SQL generation, lazy loading, caching, and batch processing, making it both powerful and efficient.</p><p>Best part? Hibernate is<strong> database-agnostic</strong>, meaning your application can switch databases with minimal code changes.</p><p>Want to dive even deeper? Well, <strong>Google is your best teacher</strong>! 😆</p><h3>What the heck is Spring Data JPA?</h3><p>Think of Spring Data JPA as JPA on steroids. It simplifies database interactions even further! Instead of dealing with boilerplate code for basic CRUD operations, Spring Data JPA wraps around JPA and gives you a cleaner, more efficient way to work with relational databases.</p><p><strong>It extends JPA by providing a set of interfaces</strong> that handle common database tasks automatically, so you don’t have to manually write queries for basic operations. Just define an interface, and off you go! Spring Data JPA generates the necessary implementations behind the scenes.</p><p>And the best part? It <strong>automatically integrates with Hibernate</strong> (or any other JPA provider you’ve configured in your Spring Boot project). So, less hassle, more productivity! 🚀</p><p>Alrighty, Let’s go and implement this.</p><p>To get started, I’m pulling in the <strong>Spring Data JPA</strong> and MySQL driver dependencies directly from <strong>Spring Initializr</strong>. Once that’s done, I’ll add it to my project’s <strong>pom.xml</strong>.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>  &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>We no longer need spring-boot-starter-jdbc since it is already packed with the JPA dependcy.</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Now, I’m going to spin up a MySQL container and create a database called Payments_Db. If you need help with that, don’t worry, I’ve added a docker-compose.yml file to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/dbs-part-2-jpa">Git repository</a> that you can use to start the container and expose the necessary ports. It’s all set up for you!</p><pre>CREATE TABLE payments<br>(<br>    payment_id     VARCHAR(255) PRIMARY KEY,<br>    initiator_id   VARCHAR(255)   NOT NULL,<br>    receiver_id    VARCHAR(255)   NOT NULL,<br>    amount         DECIMAL(10, 2) NOT NULL,<br>    initiated_time DATETIME       NOT NULL,<br>    status         VARCHAR(50)    NOT NULL<br>);<br><br>-- Inserting sample data<br>INSERT INTO payments (payment_id, initiator_id, receiver_id, amount, initiated_time, status)<br>VALUES (&#39;PAY-20250227-204927-126871628939123-00001&#39;, &#39;initiator_1&#39;, &#39;receiver_1&#39;, 150.75, &#39;2025-02-27 20:49:27&#39;,<br>        &#39;SUCCESS&#39;),<br>       (&#39;PAY-20250227-204927-126871628939123-00002&#39;, &#39;initiator_2&#39;, &#39;receiver_2&#39;, 200.50, &#39;2025-02-27 20:49:27&#39;,<br>        &#39;PENDING&#39;);</pre><p>Once the database is up and running, you can check out the tables using <strong>DBeaver</strong> (my personal favorite!) or set up a <strong>data source in IntelliJ IDEA</strong>. I won’t dive into the step-by-step details here, but don’t worry, I’ll add a <strong>screenshot for reference</strong> so you can follow along easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTjQIpOVGv6sU4qShzEIPw.png" /></figure><p>Now it’s time to update application.properties with the required configurations. Since we’re moving to MySQL, I’ve removed the previous H2 configurations. Let’s get this set up properly!</p><pre>spring.application.name=payment-manager<br><br>spring.profiles.active=MySQLRepo<br><br>####### MySQL Database related configurations ######<br>spring.datasource.url=jdbc:mysql://localhost:3306/Payments_Db<br>spring.datasource.username=root<br>spring.datasource.password=root<br># Show the sql queries in the logger.<br>spring.jpa.show-sql=true<br># (Optional) Format the logged queries for a more readable way.<br>spring.jpa.properties.hibernate.format_sql=true<br># For hibernate to generate SQL queries optimized for a Mysql database.<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect</pre><p>In our design, we need to map the Payment object to a table in the database. Let’s take a look at how we can do that with Spring Data JPA. The beauty of JPA is that it allows us to define our entities as simple Java objects, and it will automatically map those to database tables for us.</p><pre>package com.sominda.sample.payment_manager.model;<br><br>import jakarta.persistence.Column;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.EnumType;<br>import jakarta.persistence.Enumerated;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.Table;<br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br><br>import java.time.LocalDateTime;<br>import java.time.format.DateTimeFormatter;<br>import java.util.concurrent.atomic.AtomicLong;<br><br>@Getter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Entity(name = &quot;Payment&quot;)<br>@Table(name = &quot;PAYMENTS&quot;)<br>public class Payment {<br><br>    @Id<br>    @Column(name = &quot;payment_id&quot;, unique = true, nullable = false)<br>    private String paymentId;<br><br>    @Column(name = &quot;initiator_id&quot;, nullable = false)<br>    private String initiatorId;<br><br>    @Column(name = &quot;receiver_id&quot;, nullable = false)<br>    private String receiverId;<br><br>    @Column(name = &quot;amount&quot;, nullable = false)<br>    private double amount;<br><br>    @Column(name = &quot;initiated_time&quot;, nullable = false)<br>    private LocalDateTime initiatedTime;<br><br>    @Enumerated(EnumType.STRING)<br>    @Column(name = &quot;status&quot;, nullable = false)<br>    private Status status;<br><br>    private static final AtomicLong COUNTER = new AtomicLong(1);<br><br>    // This is to create a Payment object. This method will also generate a uuid for each object.<br>    public static Payment create(String initiatorId, String receiverId, double amount) {<br><br>        LocalDateTime now = LocalDateTime.now();<br>        String paymentId = generatePaymentId(now, initiatorId);<br>        return new Payment(paymentId, initiatorId, receiverId, amount, now, Status.PENDING);<br>    }<br><br>    private static String generatePaymentId(LocalDateTime dateTime, String initiatorId) {<br><br>        String formattedDate = dateTime.format(DateTimeFormatter.ofPattern(&quot;yyyyMMdd-HHmmss&quot;));<br>        long counter = COUNTER.getAndIncrement();<br>        return String.format(&quot;PAY-%s-%s-%05d&quot;, formattedDate, initiatorId.toUpperCase(), counter);<br>    }<br>}</pre><p>Alright, let’s break this down and see the magic in action! ✨</p><ul><li>@Entity : This marks our class as a JPA entity, meaning it represents a table in the database.</li><li>@Table(name = “PAYMENTS”) : This explicitly maps our entity to the <strong>“PAYMENTS” </strong>table. If we <strong>don’t specify a name, JPA defaults to the class name</strong> (Payment).</li><li>@Id: Every entity needs a primary key, and here we mark paymentId as the unique identifier for each record.</li></ul><p>Now, let’s talk about columns.</p><ul><li>@Column : This annotation customizes how a field is mapped to a database column.</li><li>name : Defines the exact column name in the table.</li><li>nullable : Helps enforce validation by specifying whether a column can be NULL.</li></ul><p>And what about enums?</p><ul><li>@Enumerated(EnumType.STRING) : This tells JPA to store the enum value as a String instead of its ordinal number.</li></ul><p>Pro tip: If you’re on a Mac, just hit <strong>Cmd + P</strong> while working in your IDE to see all the available parameters for each annotation. Just slap on a pair of brackets (e.g., @Column()), you’ll see the options!</p><p>Alright, now for the fun part. How do we actually implement the repository layer? Well, turns out it’s stupidly simple. Just <strong>define an interface</strong> and extend JpaRepository. That’s it. Spring Boot does the heavy lifting for you. Check this out:</p><pre>package com.sominda.sample.payment_manager.repository;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Profile(&quot;MySQLRepo&quot;)<br>@Repository<br>public interface PaymentsJPARepository extends JpaRepository&lt;Payment, String&gt; {<br><br>}</pre><p>That’s pretty much it! 🎉 We now have a fully implemented repository layer. Let me break down the syntax real quick. If you’re curious, just <strong>Ctrl + Click</strong> (or <strong>Cmd + Click</strong> on Mac) on JpaRepository and check out its implementation. You&#39;ll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvG7XSiFNk7fkFW984ca9Q.png" /></figure><p>Yep! By extending JpaRepository, our repository <strong>automatically</strong> inherits a bunch of useful methods from JpaRepository, ListCrudRepository, ListPagingAndSortingRepository, and QueryByExampleExecutor. So we get CRUD operations, pagination, sorting, and even dynamic queries <strong>without writing a single SQL statement</strong>. 🔥</p><p>Check out the following image of the awesome methods we get <strong>for free!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*0EfNS7Km14XLZwCAgsto1Q.png" /></figure><p>Exactly! You can just call these methods directly<strong>, </strong>no need to implement anything or write a single query. I’ll show you how to use them in a bit, but for now, just sit back and admire how <strong>ridiculously simple</strong> this is!. Of course, I can’t cover every method here, so if you’re curious, go explore and add more tools to your knowledge bank!</p><p>Yep, if you remember from my previous article, I created a common Database interface to manage all repository layers. Now, if you only have a single repository, this might feel like overengineering and that’s totally fair!</p><p>But hey, I like to stick to my patterns, so I’m doing it my way this time. You don’t have to follow this. Instead just<strong> </strong>@Autowired<strong> </strong><strong>PaymentsJPARepository</strong> inside PaymentManagerService and call the methods directly. Now, here’s how I’m rolling with it.</p><pre>package com.sominda.sample.payment_manager.repository.impl;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import com.sominda.sample.payment_manager.repository.Database;<br>import com.sominda.sample.payment_manager.repository.PaymentsJPARepository;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.List;<br><br>@Profile(&quot;MySQLRepo&quot;)<br>@Service<br>public class SQLRepository implements Database {<br><br>    @Autowired<br>    private PaymentsJPARepository paymentsJPARepository;<br><br>    @Override<br>    public void addPayment(Payment payment) {<br><br>        System.out.println(&quot;Adding payment from SQLRepository&quot;);<br>        paymentsJPARepository.save(payment);<br>    }<br><br>    @Override<br>    public Payment getPaymentById(String paymentId) {<br><br>        System.out.println(&quot;Fetching a payment from id SQLRepository&quot;);<br>        return paymentsJPARepository.findById(paymentId);<br>    }<br><br>    @Override<br>    public List&lt;Payment&gt; getAllPayments() {<br><br>        System.out.println(&quot;Fetching all payment from SQLRepository&quot;);<br>        return paymentsJPARepository.findAll();<br>    }<br>}</pre><p>Yep! That’s the beauty of <strong>Spring Data JPA, </strong>not a single SQL statement written, and it didn’t even take <strong>five minutes</strong> to set up. You might’ve noticed I didn’t slap a @Transactional on this method. That’s because Spring’s got it covered for me. For example, <strong>read-only methods</strong> like findById, automatically get @Transactional(readOnly = true), which helps avoid unnecessary database locking. And for everything else, transactions are baked in by default. But if you’re using a facade like I am, you can totally override this behavior whenever you need to.</p><h4>Why Use a Service Facade with @Transactional?</h4><p>Consider a scenario where you need to update multiple repositories within a single business operation or read from one and update another. You can create a <strong>service layer</strong> and mark the method with @Transactional to ensure atomicity. Following is a code snippet from the Spring documentation.</p><pre>@Service<br>public class UserManagementImpl implements UserManagement {<br><br>  private final UserRepository userRepository;<br>  private final RoleRepository roleRepository;<br><br>  public UserManagementImpl(UserRepository userRepository,<br>    RoleRepository roleRepository) {<br>    this.userRepository = userRepository;<br>    this.roleRepository = roleRepository;<br>  }<br><br>  @Transactional<br>  public void addRoleToAllUsers(String roleName) {<br><br>    Role role = roleRepository.findByName(roleName);<br><br>    for (User user : userRepository.findAll()) {<br>      user.addRole(role);<br>      userRepository.save(user);<br>    }<br>  }<br>}</pre><p>Now, let’s restart the server and <strong>put this baby to the test!</strong> 🔥 Now when you try out the APIs notice the logs, you can see the queries that are being executed.</p><pre>Hibernate: <br>    select<br>        p1_0.payment_id,<br>        p1_0.amount,<br>        p1_0.initiated_time,<br>        p1_0.initiator_id,<br>        p1_0.receiver_id,<br>        p1_0.status <br>    from<br>        payments p1_0</pre><p>Let’s take a moment of silence for all of us who spent hours writing boilerplate code. 🫡</p><p>Alright, now that that’s out of the way, let’s talk about writing custom queries because sometimes, the built-in ones just don’t cut it. I’m going to whip up an API to fetch payments by status. No need to go over every single class change; I’ll just focus on the SQLRepository and PaymentsJPARepository. You can find the rest of the code in my repository.</p><pre>public interface PaymentsJPARepository extends JpaRepository&lt;Payment, String&gt; {<br><br>    @Transactional(readOnly = true)<br>    @Query(&quot;SELECT p FROM Payment p WHERE p.status = :status&quot;)<br>    List&lt;Payment&gt; findAllPaymentsByStatus(Status status);<br>}</pre><p>First thing to notice is the @Transactional annotation here. It’s important to remember that declared query methods don’t get any transaction configuration applied by default. So, always make sure to add this to get the most out of Spring.</p><p>I’m using the @Query annotation here, which lets me write custom JPQL (Java Persistence Query Language) queries instead of relying on those long method naming conventions. In this query, we’re working with Payment entity objects, so p.status refers to a <strong>field in the entity, not a column</strong> in the database table. Also, :status is a <strong>named parameter,</strong> meaning it gets swapped out with the actual value at runtime. If you’re wondering how this translates to a raw SQL query, here’s what it would look like in native SQL.</p><pre>@Query(value = &quot;SELECT * FROM payments WHERE status = :status&quot;, nativeQuery = true)<br>List&lt;Payment&gt; findAllPaymentsByStatus(@Param(&quot;status&quot;) String status);</pre><p>Here, nativeQuery = true tells Spring Data JPA to run raw SQL instead of JPQL. So, payments refers to the actual table in the database, and status is the column in that table. One thing to keep in mind is that the parameter has to be a String, because native queries work directly with the database’s raw types. This is just a simple query, but there are cases where native queries are the way to go, especially when you’re optimizing for performance. Here’s my controller implementation. I know, I know, I should probably add some filter query params to make it nicer, but honestly, I just can’t be bothered this time. Let’s keep it simple for now. API best practices? We’ll tackle those another day!</p><pre>@ResponseStatus(HttpStatus.OK)<br>@GetMapping(&quot;/status/{status}&quot;)<br>public List&lt;Payment&gt; getPaymentsByStatus(@PathVariable String status) {<br><br>    return paymentManagerService.getPaymentsByStatus(status);<br>}</pre><p>Alright, let’s restart the server and give it another shot. When you hit up the new API (I’ve updated the API collection and pushed it to the <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/blob/dbs-part-2-jpa/payment-manager/src/main/resources/Spring-Demo.postman_collection.json">Git repository</a>), take a look at the console logs.</p><pre>Hibernate: <br>    select<br>        p1_0.payment_id,<br>        p1_0.amount,<br>        p1_0.initiated_time,<br>        p1_0.initiator_id,<br>        p1_0.receiver_id,<br>        p1_0.status <br>    from<br>        payments p1_0 <br>    where<br>        p1_0.status=?</pre><p>This means our custom query was executed successfully and time to celebrate! 🎉 Of course, there are plenty of other ways (and probably better ways) to implement this, but hey, this is just one way to get it done.</p><p>For your reference, I’ve added a way to implement pagination at the end of the SQLRepository class. Check it out if you&#39;re interested!</p><pre>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.PageRequest;<br>import org.springframework.data.domain.Pageable;<br>import org.springframework.data.domain.Sort;</pre><pre>private List&lt;Payment&gt; getAllPaymentsWithPagination(int page, int size) {<br><br>    Pageable pageable = PageRequest.of(page, size, Sort.by(&quot;initiatedTime&quot;).descending());<br>    Page&lt;Payment&gt; paymentPage = paymentsJPARepository.findAll(pageable);<br>    return paymentPage.getContent(); // Get the list of payments from the Page object<br>}</pre><p>Yep, that’s all about the databases for now. It’s been a bit of a whirlwind, but I’ll try to be more descriptive if I have more time in the future! There’s a lot more to explore, but we’ve covered the essentials. Hopefully, this gives you a solid starting point. I’ll be adding all of this to my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/dbs-part-2-jpa">repository</a> (make sure to check out the branches, as they contain the relevant code for each step).</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f6fd0cb238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: Adding a database layer (Part 1)]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-adding-a-database-layer-part-1-fef164ec0edd?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/fef164ec0edd</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-jdbc]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 03:16:59 GMT</pubDate>
            <atom:updated>2025-03-01T20:30:07.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-JZtNsI17u8QojaozSNbw.png" /></figure><p>So, in my <a href="https://somindagamage.medium.com/spring-boot-for-beginners-how-to-build-a-simple-web-server-0070235ce459">last article</a>, I showed you how to write a service. But what’s the point if you can’t get your hands on any data from the database, right? Well, don’t worry. I’ve got you! In this one, I’m going to walk you through how to connect your app to a database (and I’ll do my best to give you a solid understanding of the basics).</p><p>Let’s jump into it!</p><p>In Spring Boot, the @Repository annotation is used to define a Data Access Object (DAO) and facilitate interaction with the database. So let’s start from there.</p><pre>package com.sominda.sample.payment_manager.repository.impl;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import com.sominda.sample.payment_manager.repository.Database;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.stereotype.Repository;<br><br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>@Profile(&quot;MyBasicRepo&quot;)<br>@Repository(&quot;MapDatabaseRepository&quot;)<br>public class MapDatabaseRepository implements Database {<br><br>    private final Map&lt;String, Payment&gt; database = new HashMap&lt;&gt;();<br><br>    @Override<br>    public void addPayment(Payment payment) {<br><br>        System.out.println(&quot;addPayment Using the repository in MapDatabaseRepository&quot;);<br>        database.put(payment.getPaymentId(), payment);<br>    }<br><br>    @Override<br>    public Payment getPaymentById(String paymentId) {<br><br>        System.out.println(&quot;getPaymentById Using the repository in MapDatabaseRepository&quot;);<br>        return database.get(paymentId);<br>    }<br><br>    @Override<br>    public List&lt;Payment&gt; getAllPayments() {<br><br>        System.out.println(&quot;getAllPayments Using the repository in MapDatabaseRepository&quot;);<br>        return new ArrayList&lt;&gt;(database.values());<br>    }<br>}</pre><p>So, to start things off, I’ve created a new repository called MapDatabaseRepository just to show you the format (I know, I know, you’d probably never use this in a real-world project. But hang in there with me for now, this is just to get you warmed up). The Database here is an interface I created to initialize multiple repository interfaces. Why? Well, this makes it easier for me to implement different data sources later on in the demo without needing to change much of the existing code.</p><p>Notice that I’ve added the @Repository(“MapDatabaseRepository”) annotation. This is pretty useful if you ever want to explicitly define the name of the bean in the Spring application context instead of letting Spring decide the default name for you.</p><p>Here’s an example of how it works, but don’t worry, I won’t actually be using this in the demo. This is just a little something for your knowledge.</p><pre>@Autowired<br>@Qualifier(&quot;MapDatabaseRepository&quot;)<br>private Database Database;</pre><p>When you’re developing, there will be times when you need to change the behavior of your app depending on the environment it’s running in. That’s where the @Profile annotation comes in handy. It lets you define a set of beans that are only available in specific environments or configurations.</p><p>For example, I’ve added @Profile here so that this bean will only be available when I set the profile to <strong>“</strong>MyBasicRepo<strong>”</strong> (don’t worry, I’ve got bigger plans for repositories down the line 😉).</p><p>There are several ways to set the profile, but for now, I’m keeping it simple and specifying the profile in <strong>application.properties</strong>.</p><pre>spring.profiles.active=MyBasicRepo</pre><p><strong>P.S.</strong>: Just a quick note on the <strong>application.properties</strong> file. It is used for <strong>externalizing configuration properties</strong> in your application. This means you can easily change settings without touching your code, making it more flexible and environment-friendly. Pretty neat, right?</p><p>To wire in the new repository, you can simply use @Autowired with the interface (I’m sure you remember @Autowired from the last blog, where we covered it in detail). See where I’m going with this? By implementing a common interface for all repository types, it makes everything super easy to plug and play. Pretty <strong>genius</strong>, right? 😎</p><pre>package com.sominda.sample.payment_manager.service;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import com.sominda.sample.payment_manager.repository.Database;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public class PaymentManagerService {<br><br>    @Autowired<br>    Database database;<br><br>    public void initiatePayment(Payment payment) {<br><br>        database.addPayment(payment);<br>    }<br><br>    public Payment getPaymentByID(String paymentId) {<br><br>        return database.getPaymentById(paymentId);<br>    }<br><br>    public List&lt;Payment&gt; getAllPayments() {<br><br>        return database.getAllPayments();<br>    }<br>}</pre><p>Alright, time to restart the service once again! When it starts up, take a look at the log. If everything’s working properly, you should see the profile you’ve set. If it’s not set, you’ll see <strong>“</strong>Default<strong>”</strong> instead.</p><pre>2025-02-27T20:49:14.889-05:00  INFO 7354 --- [payment-manager] [main] c.s.s.p.PaymentManagerApplication: The following 1 profile is active: &quot;MyBasicRepo&quot;</pre><p>Now, go ahead and play around with the APIs. Try hitting them and see if you can spot the print messages we added. If you see them pop up, then <strong>congratulations</strong>.</p><p>Alright, now let’s try something a bit more interesting: setting up an <strong>H2 in-memory database</strong> and see how we can get that working. I’m going to show you the most basic way to do this.</p><p>To get started, you’ll need to add the following two dependencies. You can grab them easily from <strong>Spring Initializr</strong>. Don’t worry, you don’t need to download the whole zip again. Just hit the <strong>Explore</strong> button, and you can copy the dependencies directly from the <strong>pom.xml</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GOi8uc8q5JDgjyfv65kQNg.png" /></figure><p>Add the following to the <strong>application.properties</strong> file. Note that I have changed the profile this time.</p><pre>spring.profiles.active=H2Repo<br><br>###### Database related configurations ######<br># Access the h2 console from browser.<br>spring.h2.console.enabled=true<br>spring.datasource.generate-unique-name=false<br>spring.datasource.name=Payments_Db<br>spring.datasource.username=sa<br># No password is set here.<br># spring.datasource.password=sa<br><br># Add this when the script needs to execute. Usually this is done for the H2 in-memory dbs.<br>spring.sql.init.mode=always<br># Add this to init schema if the schema.sql file is not in the resources directory.<br>spring.sql.init.schema-locations=classpath:dbscripts/h2/schema.sql</pre><p>So, to make sure the tables are created when the application starts, I’ve added a simple configuration spring.sql.init.mode=always. This tells Spring Boot to run a script during startup that’ll create the necessary database tables.</p><p>Now, all you need to do is create a <strong>schema.sql</strong> file and place it in the location specified by the config spring.sql.init.schema-locations. Just a heads-up, the path starts from the <strong>resources</strong> directory, so make sure it’s in the right spot.</p><pre>DROP TABLE IF EXISTS payments;<br><br>CREATE TABLE payments (<br>  payment_id VARCHAR(255) PRIMARY KEY,<br>  initiator_id VARCHAR(255) NOT NULL,<br>  receiver_id VARCHAR(255) NOT NULL,<br>  amount DECIMAL(10, 2) NOT NULL,<br>  initiated_time TIMESTAMP NOT NULL,<br>  status VARCHAR(50) NOT NULL<br>);<br><br>-- Inserting sample data (Optional)<br>INSERT INTO payments (payment_id, initiator_id, receiver_id, amount, initiated_time, status)<br>VALUES<br>    (&#39;PAY-20250227-204927-126871628939123-00001&#39;, &#39;initiator_1&#39;, &#39;receiver_1&#39;, 150.75, &#39;2025-02-27 20:49:27&#39;, &#39;SUCCESS&#39;),<br>    (&#39;PAY-20250227-204927-126871628939123-00002&#39;, &#39;initiator_2&#39;, &#39;receiver_2&#39;, 200.50, &#39;2025-02-27 20:49:27&#39;, &#39;PENDING&#39;);</pre><p>With those configurations in place, your application will start up an instance of H2 and run the database scripts before it starts serving any requests. Now that the database is all set up, let’s take a look at how the repository layer is implemented.</p><pre>package com.sominda.sample.payment_manager.repository.impl;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import com.sominda.sample.payment_manager.model.Status;<br>import com.sominda.sample.payment_manager.repository.Database;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.dao.EmptyResultDataAccessException;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.stereotype.Repository;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import java.sql.ResultSet;<br>import java.sql.SQLException;<br>import java.sql.Timestamp;<br>import java.time.LocalDateTime;<br>import java.util.List;<br><br>@Profile(&quot;H2Repo&quot;)<br>@Repository(&quot;H2InMemoryRepository&quot;)<br>public class H2InMemoryRepository implements Database {<br><br>    @Autowired<br>    JdbcTemplate jdbcTemplate;<br><br>    @Transactional<br>    @Override<br>    public void addPayment(Payment payment) {<br><br>        String sql = &quot;INSERT INTO PAYMENTS (PAYMENT_ID, INITIATOR_ID, RECEIVER_ID, AMOUNT, INITIATED_TIME, STATUS) &quot; +<br>                &quot;VALUES (?,?,?,?,?,?)&quot;;<br>        jdbcTemplate.update(sql, payment.getPaymentId(), payment.getInitiatorId(), payment.getReceiverId(),<br>                payment.getAmount(), payment.getInitiatedTime(),payment.getStatus().toString());<br>    }<br><br>    private static Payment rowMapper(ResultSet rs, int rowId) throws SQLException {<br><br>        Timestamp timestamp = rs.getTimestamp(&quot;INITIATED_TIME&quot;);<br>        LocalDateTime initiatedTime = timestamp != null ? timestamp.toLocalDateTime() : null;<br><br>        String statusStr = rs.getString(&quot;STATUS&quot;);<br>        Status status = statusStr == null ? null : Status.valueOf(statusStr);<br><br>        return new Payment(rs.getString(&quot;PAYMENT_ID&quot;),<br>                rs.getString(&quot;INITIATOR_ID&quot;),<br>                rs.getString(&quot;RECEIVER_ID&quot;),<br>                rs.getDouble(&quot;AMOUNT&quot;),<br>                initiatedTime,<br>                status<br>        );<br>    }<br><br>    @Override<br>    public Payment getPaymentById(String paymentId) {<br><br>        String sql = &quot;SELECT * FROM PAYMENTS WHERE PAYMENT_ID = ?&quot;;<br>        Payment payment = null;<br>        try {<br>            payment = jdbcTemplate.queryForObject(sql, H2InMemoryRepository::rowMapper, paymentId);<br>        } catch (EmptyResultDataAccessException e) {<br>            System.out.println(&quot;No payment found with id &quot; + paymentId);<br>        }<br>        return payment;<br>    }<br><br>    @Override<br>    public List&lt;Payment&gt; getAllPayments() {<br><br>        String sql = &quot;SELECT * FROM PAYMENTS&quot;;<br>        List&lt;Payment&gt; payments = null;<br>        try {<br>            payments = jdbcTemplate.query(sql, H2InMemoryRepository::rowMapper);<br>        } catch (EmptyResultDataAccessException e) {<br>            System.out.println(&quot;No payment founds&quot;);<br>        }<br>        return payments;<br>    }<br>}</pre><p>Now, take a moment to spot the difference between this bean and the one we used earlier. I’ve added the @Transactional annotation. Why? Because this ensures that the method (or all methods in the class if applied at the class level) runs <strong>within a database transaction</strong>. So, if anything goes wrong during execution, the transaction automatically <strong>rolls back</strong>, keeping the database in a clean state.</p><p>Next, I’ve used @Autowired JdbcTemplate jdbcTemplate. This injects an instance of JdbcTemplate, which is a handy tool for interacting with relational databases using <strong>JDBC</strong> db without all the usual boilerplate code.</p><p>Now, here’s something important: rowMapper. This method is used to convert a database row into a Payment object because JDBC operations return raw ResultSet objects. By using rowMapper, we neatly transform those raw database rows into something we can actually use in our application. Now, I know there are way better ways to handle this (up next), but let’s not get ahead of ourselves. We’ll stick to this approach for now — just to keep things simple and easy to follow.</p><p>Alright, time to restart the service once again! When it starts up, notice the following logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGvpFc81gXDUHqd-bYh41A.png" /></figure><p>See how our <strong>application.properties</strong> configs just took care of setting up the database? <strong>Spring Boot does the heavy lifting for us! </strong>Now, head over to <a href="http://localhost:8080/h2-console"><strong>http://localhost:8080/h2-console</strong></a>. You’ll need the <strong>URL and username</strong> printed in the startup logs, so grab those first. Once you’re in, you should see the initial data we set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRRkWmOgr55WY-S0XB7u2Q.png" /></figure><p>Now, go ahead and tryout the APIs. Try making some requests and watch how the data gets added and retrieved in real-time.</p><p>Did you just see what we pulled off? <strong>We wrote a full set of CRUD operations in just a few lines of code!</strong> 😲 Seriously, look at how <strong>effortless</strong> Spring Boot makes this. That’s the real power of the framework. It takes care of all the heavy lifting so we can focus on what actually matters.</p><p>Next up, we’ll dive into interacting with a <strong>MySQL database</strong>. But for now, I think we’ve covered enough ground. The next part involves quite a bit of new stuff, and adding it here would make things way too long. So, stay tuned for <strong>using JPA</strong> to interact with databases!</p><p>I’ll be adding all of this to <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/dbs-part-1">my repository</a> (make sure to check out the branches, as they contain the relevant code for each step), and you’ll find the <strong>Postman collection</strong> for the APIs there as well. So go ahead and check it out when you can! 😊</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fef164ec0edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot for Beginners: How to Build a Simple Web Server]]></title>
            <link>https://somindagamage.medium.com/spring-boot-for-beginners-how-to-build-a-simple-web-server-0070235ce459?source=rss-ff0a15b74cca------2</link>
            <guid isPermaLink="false">https://medium.com/p/0070235ce459</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Sominda Gamage]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 22:16:04 GMT</pubDate>
            <atom:updated>2025-02-27T22:39:26.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://www.devopsschool.com/blog/what-is-spring-boot-and-use-cases-of-spring-boot/"><img alt="Image from : https://www.devopsschool.com/blog/what-is-spring-boot-and-use-cases-of-spring-boot/" src="https://cdn-images-1.medium.com/max/1024/1*os-kEY6vkmhbx3TEznlOng.png" /></a></figure><p>Spring Boot is a Java-based framework that makes building Spring applications stupid easy. Honestly, it’s one heck of a tool for whipping up stand-alone, production-ready apps that “<em>Just Run” </em>without a ton of setup.</p><p>Here’s why I love using Spring Boot for microservices:</p><ul><li><strong>Auto-configuration magic — </strong>No more drowning in boilerplate code! Spring Boot takes care of the heavy lifting with sensible defaults, so you spend less time tweaking configs and more time building cool stuff.</li><li><strong>Built-in server? Yes, please!</strong> — No need to mess around with setting up Tomcat or Jetty separately. Just package your app and boom, it runs like a champ.</li></ul><p>There are tons of other cool features that make Spring Boot a favorite among devs, but I’m not gonna get into all that here. This is for dummies like me who just wanna build a microservice without getting lost in the weeds.</p><p>I’m putting together a series of articles to walk you through the basics — setting up a microservice, connecting to a database, handling transactions, dealing with exceptions, and securing API endpoints with tokens. Just the good stuff to get you up and running.</p><p>This won’t make you a Spring Boot guru overnight, but it’ll give you a solid foundation. After that, it’s up to you to tinker, break things, and level up!</p><figure><a href="https://depositphotos.com/vectors/lets-go.html"><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BLWHoIZB-7m3e_7WtI4a0Q.jpeg" /></a></figure><p>Alright, so a good place to kick things off is <strong>Spring Initializr</strong> which is an online tool that helps you whip up a Spring Boot project with just the right dependencies, no fuss. Here’s the sample project I created:</p><ul><li><strong>Build Tool:</strong> Maven</li><li><strong>Java Version:</strong> 21</li><li><strong>Spring Boot Version:</strong> 3.4.3</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNzyU4pKeT5gY7faMvVgQg.png" /></figure><p>Now, let’s add the <strong>spring-boot-starter-web</strong> dependency. This is essential for running our application as a web server. Once added, head over to the <strong>“Explore”</strong> section to check out the pom.xml and the project structure. If everything looks good, smash that <strong>&quot;Generate&quot;</strong> button to download the project.</p><p>For development, I’m rolling with <strong>IntelliJ IDEA Ultimate</strong> which is my all-time favorite IDE. (Nope, I’m not getting a sponsorship. Wish I was, though! 😆) The best part? It comes with the <strong>Spring plugin</strong> enabled out of the box.</p><p>Inside the project tree, you will see the following class.</p><pre>package com.sominda.sample.payment_manager;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class PaymentManagerApplication {<br><br>    public static void main(String[] args) {<br><br>        SpringApplication.run(PaymentManagerApplication.class, args);<br>    }<br>}</pre><p>Now, go ahead and run the class(or just the main method). Once it starts up, you’ll notice something interesting in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcRrSpBoJ1-c4RkfwPqUtw.png" /></figure><p>This means your application is now up and running on <strong>port 8080</strong> with an embedded <strong>Tomcat</strong> server. 🎉 Now, open your browser and go to <a href="http://localhost:8080/"><strong>http://localhost:8080/</strong></a>. You’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*NYFX-W9tiJ3wyStf-ZQkxQ.png" /></figure><p>Does this mean an error? Nahhh…!!! Turns out, we’ve just created the most basic web server. The @<em>SpringBootApplication </em>annotation and calling the run() method are literally all you need to kickstart a server.</p><p>Can you see how ridiculously simple this is? Just a few lines of code and <strong>boom</strong>, we’ve got a running server without breaking a sweat. 😎</p><p>Alright, enough with the error pages! We’re here to generate some <strong>endpoints</strong>, not watch Spring Boot throw default error screens at us. 😆</p><p>So let’s dive into how we can actually implement some real endpoints. Get ready to start building! 🚀</p><pre>package com.sominda.sample.payment_manager.controller;<br><br>import org.springframework.http.HttpStatus;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.ResponseStatus;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1/payment&quot;)<br>public class PaymentController {<br><br>    @ResponseStatus(HttpStatus.OK)<br>    @GetMapping(&quot;&quot;)<br>    public String getAllPayment() {<br><br>        return &quot;Here are your payments&quot;;<br>    }<br><br>    @ResponseStatus(HttpStatus.OK)<br>    @GetMapping(&quot;/{id}&quot;)<br>    public String getPaymentById(@PathVariable String id) {<br><br>        return &quot;Here is your payment by id: &quot; + id;<br>    }<br><br>    @ResponseStatus(HttpStatus.CREATED)<br>    @PostMapping(&quot;&quot;)<br>    public String payUser(){<br>        return &quot;Payment done&quot;;<br>    }<br>}</pre><p>What’s this? Yup, that’s all we need to expose three endpoints like these:</p><ul><li><strong>Fetch all payments: </strong>GET /api/v1/payment → Returns <strong>200 OK</strong></li><li><strong>Fetch a specific payment: </strong>GET /api/v1/payment/{id} → Returns <strong>200 OK</strong></li><li><strong>Initiate a payment: </strong>POST /api/v1/payment → Returns <strong>201 Created</strong></li></ul><p>I know, these are just returning Strings, and the payUser method doesn’t take any input yet. But hey, let’s start with baby steps. Once we’ve got the basics down, we can move on to more advanced stuff. Let’s see what I have done.</p><p>Here I created a PaymentController class. This is where the magic happens as I’ll be putting all the API logic in here. Then, I marked the class with @RestController. Why? Well, this annotation turns the class into a controller that handles HTTP requests and returns <strong>JSON</strong>. It’s basically a combo of @Controller and @ResponseBody, meaning Spring Boot will automatically serialize any objects you return into the HTTP response body. No extra work needed.</p><p>Next, I used @RequestMapping(“/api/v1/payment”) on the class level. This is what maps the controller to the base API path, so I can easily create nested resources later on if needed. For the getAllPayment method, I wanted it to match the base path exactly. So, I marked it with @GetMapping(“”) &gt; the empty string means it’ll use the same path as the class, i.e., /api/v1/payment. And since it’s a <strong>GET</strong> request, @GetMapping is perfect for that. I also set the response code to <strong>HTTP 200 OK</strong>, because that’s what you want when you successfully fetch all payments.</p><p>Next, let’s tackle getting a specific payment using a UUID using the getPaymentById method. Notice how I used @GetMapping(“/{id}”) where the {id} in the path makes it easy to grab a specific payment by its <strong>uuid</strong>. This automatically maps the API to /api/v1/payment/&lt;id&gt;.</p><p>To access that <strong>uuid</strong> value, I used the @PathVariable annotation with method parameters. This allows me to retrieve the <strong>id</strong> from the URL and use it inside the method. Cool, right?</p><p>Finally, to initiate a payment, I used @PostMapping(“”).This makes it a <strong>POST</strong> request that’s mapped to the base API path, /api/v1/payment. Since we&#39;re creating a new resource, I made sure it returns an <strong>HTTP 201 Created</strong> response. Perfect for when you&#39;re initiating a new payment.</p><p>Now, go ahead and try out these endpoints with <strong>Postman</strong> (and no, I’m not getting a sponsorship 😆).</p><p>Alright, now let’s get to the good stuff, API requests and response bodies! For this, I’ve created a few classes that handle the request and response logic. You can find all these in my <a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/initial-impl">Git repo</a>, so feel free to check them out and follow along.</p><pre>package com.sominda.sample.payment_manager.model;<br><br>public enum Status {<br>    PENDING,<br>    PROCESSING,<br>    SUCCESS,<br>    FAILED<br>}</pre><pre>package com.sominda.sample.payment_manager.model.api;<br><br>import com.sominda.sample.payment_manager.model.Status;<br><br>public record PaymentInitiatorResponse(String paymentId, Status status) { }</pre><pre>package com.sominda.sample.payment_manager.model.api;<br><br>public record PaymentRequest (String initiator, String receiver, double amount) { }</pre><p>Now, let’s take a look at the improvement I made to handle the payment initiation request.</p><pre>@ResponseStatus(HttpStatus.CREATED)<br>@PostMapping(&quot;&quot;)<br>public PaymentInitiatorResponse payUser(@RequestBody PaymentRequest paymentRequest) {<br><br>    System.out.println(String.format(&quot;Payment request from: %s to user: %s&quot;, paymentRequest.initiator(),<br>            paymentRequest.receiver()));<br>    return new PaymentInitiatorResponse(&quot;1234&quot;, PENDING);<br>}</pre><p>Notice the @RequestBody annotation. This tells Spring to expect a request body that’s mapped to the PaymentRequest class. So, whenever we initiate a payment, the request will carry all the necessary data in the body. Also, check out how the response is created using the PaymentInitiatorResponse class. It’s pretty straightforward, right? We take the input, process it, and send a nicely formatted response back.</p><p>Alright, now go ahead and <strong>restart the server</strong> and give the <strong>POST</strong> request another shot. But this time, make sure you’ve got the body parameters set up correctly. You want to make sure the request body contains the necessary data in the right format so your API can process it properly.</p><pre>curl --location &#39;http://localhost:8080/api/v1/payments&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;initiator&quot;: &quot;126871628939123&quot;,<br>    &quot;receiver&quot;: &quot;126871628939123&quot;,<br>    &quot;amount&quot;: 100<br>}&#39;</pre><p>See how easy that is? Just a few annotations and you’re up and running with a working API server. The real beauty of Spring Boot is the convenience it offers. It takes care of so much for you out of the box such as configuring the server, handling requests, and serializing objects enabling you to focus on building the actual business logic.</p><p>Let’s add a little extra polish to the project with some nice functionality. To make things cleaner and more organized, I’m moving the <strong>payment logic</strong> into a service layer. This separates concerns and makes the code easier to maintain. 🎯</p><p>Take a look at the following classes. Also, I’ve added the <strong>Project Lombok</strong> dependency to the <strong>pom.xml</strong>. This is a neat little tool that reduces boilerplate code like getters, setters, and constructors. It’s a total lifesaver!</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>  &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>  &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><pre>package com.sominda.sample.payment_manager.model;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br><br>import java.time.LocalDateTime;<br>import java.time.format.DateTimeFormatter;<br>import java.util.concurrent.atomic.AtomicLong;<br><br>@Getter<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Payment {<br><br>    private String paymentId;<br>    private String initiatorId;<br>    private String receiverId;<br>    private double amount;<br>    private LocalDateTime initiatedTime;<br>    private Status status;<br><br>    private static final AtomicLong COUNTER = new AtomicLong(1);<br><br>    // This is to create a Payment object. This method will also generate a uuid for each object.<br>    public static Payment create(String initiatorId, String receiverId, double amount) {<br><br>        LocalDateTime now = LocalDateTime.now();<br>        String paymentId = generatePaymentId(now, initiatorId);<br>        return new Payment(paymentId, initiatorId, receiverId, amount, now, Status.PENDING);<br>    }<br><br>    private static String generatePaymentId(LocalDateTime dateTime, String initiatorId) {<br><br>        String formattedDate = dateTime.format(DateTimeFormatter.ofPattern(&quot;yyyyMMdd-HHmmss&quot;));<br>        long counter = COUNTER.getAndIncrement();<br>        return String.format(&quot;PAY-%s-%s-%05d&quot;, formattedDate, initiatorId.toUpperCase(), counter);<br>    }<br>}</pre><pre>package com.sominda.sample.payment_manager.service;<br><br>import com.sominda.sample.payment_manager.model.Payment;<br>import org.springframework.stereotype.Service;<br><br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>@Service<br>public class PaymentManagerService {<br><br>    private final Map&lt;String, Payment&gt; database = new HashMap&lt;&gt;();<br><br>    public void initiatePayment(Payment payment) {<br><br>        database.put(payment.getPaymentId(), payment);<br>    }<br><br>    public Payment getPaymentByID(String paymentId) {<br><br>        return database.get(paymentId);<br>    }<br><br>    public List&lt;Payment&gt; getAllPayments() {<br><br>        return new ArrayList&lt;&gt;(database.values());<br>    }<br>}</pre><p>In the PaymentManagerService class, I’ve used the @Service annotation. This indicates that the class handles some <strong>service-related logic</strong>, like business rules or operations.</p><p>I’ve also made some improvements to the PaymentController. By delegating the heavy lifting to the PaymentManagerService, the controller is now cleaner, easier to maintain, and follows best practices for separation of concerns.</p><pre>@RestController<br>@RequestMapping(&quot;/api/v1/payments&quot;)<br>public class PaymentController {<br><br>    @Autowired<br>    PaymentManagerService paymentManagerService;<br><br>    @ResponseStatus(HttpStatus.OK)<br>    @GetMapping(&quot;&quot;)<br>    public List&lt;Payment&gt; getAllPayment() {<br><br>        return paymentManagerService.getAllPayments();<br>    }<br><br>    @ResponseStatus(HttpStatus.OK)<br>    @GetMapping(&quot;/{id}&quot;)<br>    public Payment getPaymentById(@PathVariable String id) {<br><br>        return paymentManagerService.getPaymentByID(id);<br>    }<br><br>    @ResponseStatus(HttpStatus.CREATED)<br>    @PostMapping(&quot;&quot;)<br>    public PaymentInitiatorResponse payUser(@RequestBody PaymentRequest paymentRequest) {<br><br>        Payment payment = Payment.create(paymentRequest.initiator(), paymentRequest.receiver(),<br>                paymentRequest.amount());<br>        paymentManagerService.initiatePayment(payment);<br>        return new PaymentInitiatorResponse(payment.getPaymentId(), payment.getStatus());<br>    }<br>}</pre><p>Here comes the magic. Notice how I used @Autowired annotation to wire my service layer with the controller. This follows <strong>dependency injection</strong>, which is <strong>a fundamental feature of the Spring Framework</strong>. This allows us to automatically inject dependencies (objects that a class depends on) into a Spring-managed bean at runtime, instead of manually instantiating them. This helps in decoupling the components, making the system more modular, testable, and easier to manage.</p><p>Alright, now that we’ve made some improvements, it’s time to <strong>restart the service</strong> and test the API requests once again.</p><p>Here are some sample requests and their corresponding responses:</p><pre>curl --location &#39;http://localhost:8080/api/v1/payments&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;initiator&quot;: &quot;126871628939123&quot;,<br>    &quot;receiver&quot;: &quot;126871628939123&quot;,<br>    &quot;amount&quot;: 100<br>}&#39;</pre><pre>{<br>    &quot;paymentId&quot;: &quot;PAY-20250227-162143-126871628939123-00002&quot;,<br>    &quot;status&quot;: &quot;PENDING&quot;<br>}</pre><pre>curl --location &#39;http://localhost:8080/api/v1/payments/PAY-20250227-161130-126871628939123-00001&#39;</pre><pre>{<br>    &quot;paymentId&quot;: &quot;PAY-20250227-161130-126871628939123-00001&quot;,<br>    &quot;initiatorId&quot;: &quot;126871628939123&quot;,<br>    &quot;receiverId&quot;: &quot;126871628939123&quot;,<br>    &quot;amount&quot;: 100.0,<br>    &quot;initiatedTime&quot;: &quot;2025-02-27T16:11:30.028312&quot;,<br>    &quot;status&quot;: &quot;PENDING&quot;<br>}</pre><p><strong>Congratulations!</strong> 🎉 You’ve just implemented a fully working web server with Spring Boot. This is a huge step! I think this is a great place to stop for now. You can find the complete <strong><em>sample code in my GitHub repo </em></strong><a href="https://github.com/somindatommy/SpringBoot-For-Beginners/tree/initial-impl"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p>Next, I’m thinking of diving into the <strong>DB layer</strong> to make the app persistent. I’ll upload all of this to my <strong>GitHub</strong>, and I’ll link it here so you can grab the code and follow along.</p><p>And hey, if you’ve learned something from this blog, don’t forget to <strong>applaud</strong>! 🙌 Your feedback means the world to me. Thanks for following along, and stay tuned for the next part! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0070235ce459" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>