Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 50

Splitting a Monolith into Spring Boot Microservices

This lesson is built with resources from youtube.com, freecodecamp.org and 1 more site.

Introduction

In our last lesson, we put on our architect hats and designed the blueprint for our microservices architecture. We defined the clear boundaries for an Auth Service and a Blog Service and outlined their API contracts. This conceptual work is the bedrock of any successful distributed system.

Today, we transition from architect to builder. We will execute that blueprint by performing a hands-on refactoring of our monolithic application. Our goal is to physically split our single codebase into two new, independent, and runnable Spring Boot projects. By the end of this lesson, you will have two distinct services running on your machine, each responsible for its own domain.

MERN Stack Comparison

Think of this process in the context of your MERN experience. It's equivalent to realizing your single, large Express.js application has become too complex. You decide to split it into two separate Node.js projects: one for handling user authentication and another for managing blog posts. Each would have its own package.json, its own server.js file, run on a different port, and connect to its own database schema. That's precisely what we are about to do with Spring Boot.


The "Why" and "How" of the Split

Before we start moving files, let's visualize the goal. We're moving from a single application where all code lives together to a structure where each service is a self-contained project.

Monolith VS. Microservice Architecture Comparison
This image clearly shows our goal. We are moving from the model on the left, where modules communicate internally within a single deployment, to the model on the right, where each module is an independent service that will eventually communicate over the network.

The process of splitting a monolith involves creating new projects, migrating the relevant code, and, most importantly, severing the direct dependencies between the components that now live in different services.

To guide you through this hands-on process, we will use a comprehensive video that demonstrates this exact refactoring pattern.

Converting Job App to Individual Microservices | Spring Boot REST API to Microservices | Video #7

This video from EmbarkX, titled 'Converting Job App to Individual Microservices', is an excellent, step-by-step guide for our task. The instructor refactors a monolith into Job, Company, and Review microservices. We will follow the same core principles for our Auth and Blog services.

Watch the segment from 00:00:58 to 00:18:21. Focus on these key activities: Project Creation: How a new Spring Boot project is created for the 'Job' microservice using Spring Initializr. Code Migration: The process of copying the job package into the new project. Decoupling Entities: Pay close attention at 09:52. This is the most critical part. Notice how the Job entity's relationship to the Company entity is changed from a direct object reference (private Company company;) to a simple ID (private long companyId;). Configuration: How the new service is configured to run on a different port (8082).


Your Task: The Great Refactor

Now it's your turn to apply these steps to our blog platform. We will break this down into a few manageable parts.

Part 1: Project Scaffolding

First, create the two new, empty Spring Boot projects that will house our services.

  1. Go to Spring Initializr.
  2. Create the auth-service project with the following dependencies:
    • Spring Web
    • Spring Data JPA
    • PostgreSQL Driver
    • Spring Security
    • Lombok (for convenience)
  3. Create the blog-service project with these dependencies:
    • Spring Web
    • Spring Data JPA
    • PostgreSQL Driver
    • Spring Security (we still need to secure its endpoints)
    • Lombok

Download and unzip both projects into a common parent directory.

Part 2: Code Migration

Now, we'll move the existing code from our monolith into the appropriate new service.

  1. For auth-service: Copy the following files/packages from your original monolithic project into the auth-service's src/main/java/ directory:

    • The User entity.
    • The UserRepository interface.
    • The UserService and its implementation.
    • The AuthController.
    • Your entire security package, including SecurityConfig, JWT filters, and related classes.
    • Any related DTOs for user registration and login.
  2. For blog-service: Copy these files into the blog-service project:

    • The Post entity.
    • The PostRepository interface.
    • The PostService and its implementation.
    • The PostController.
    • Any related DTOs for creating/updating posts.

At this point, your blog-service project will have many compilation errors, especially in the Post entity. This is expected and brings us to the most important step.

Part 3: Decoupling the Services

The compilation errors exist because the Post entity has a direct dependency on the User entity, which no longer exists in the blog-service's classpath. We need to break this tight coupling.

In your blog-service project:

  1. Modify the Post Entity:

    • Open the Post entity class.
    • Find the field private User author; which is likely annotated with @ManyToOne.
    • Delete this entire field.
    • Add a new field: private Long authorId;.
    • Make sure you have getters and setters for this new field.
  2. Fix the PostService:

    • Your service logic for creating a post likely took a User object to set the author.
    • Modify the createPost method. It should now accept an authorId (of type Long) as a parameter.
    • Inside the method, instead of post.setAuthor(user), you will now do post.setAuthorId(authorId).
    • You will need to adjust any other methods (like update or delete logic) that previously relied on the User object. For now, our primary focus is on establishing the new relationship.

This change is the essence of this refactoring. The Blog Service no longer knows anything about the User entity's structure (like username or email). It only cares about the authorId, a simple foreign key. It treats the user as an opaque reference.

Part 4: Configuration and Isolation

Each service must run independently. This requires separate configurations.

  1. Create Databases: In pgAdmin, create two new, empty databases: blog_auth_db and blog_content_db.

  2. Configure auth-service: In its src/main/resources/application.yml file, add the following:

    server:
      port: 8081
    
    spring:
      application:
        name: auth-service
      datasource:
        url: jdbc:postgresql://localhost:5432/blog_auth_db
        username: your_postgres_user
        password: your_postgres_password
      jpa:
        hibernate:
          ddl-auto: update
        show-sql: true
    
  3. Configure blog-service: In its src/main/resources/application.yml file, add:

    server:
      port: 8082
    
    spring:
      application:
        name: blog-service
      datasource:
        url: jdbc:postgresql://localhost:5432/blog_content_db
        username: your_postgres_user
        password: your_postgres_password
      jpa:
        hibernate:
          ddl-auto: update
        show-sql: true
    

Running and Verifying the Services

With our code migrated and configured, it's time to bring our new services to life. It's often useful to manage multiple related projects within a single IDE window.

Converting Job App to Individual Microservices | Spring Boot REST API to Microservices | Video #7

Let's watch a short segment from the same video that shows how to add multiple Maven projects into a single IntelliJ IDEA window. This makes it much easier to run, debug, and view the logs for all your services at once.

Watch from 00:57:17 to 01:03:09. The instructor demonstrates how to use the 'Maven' tool window in IntelliJ to link multiple projects together and use the 'Services' tab to manage them all.

Follow the video's instructions to open both auth-service and blog-service in the same IntelliJ window.

Now, run both applications. Check the console logs. You should see auth-service start on port 8081 and blog-service start on port 8082.

Verification with Postman

Let's confirm the services are working independently.

  1. Test auth-service: Send a POST request to http://localhost:8081/api/v1/auth/register with a new user's details. You should get a 201 Created response. Check your blog_auth_db to see the new user in the users table.

  2. Test blog-service: Before we can test this, we have a problem. The endpoints in blog-service are secured, but the service has no way to validate a user yet. For this lesson's verification purposes only, we'll temporarily disable security on the post endpoints. In your blog-service's SecurityConfig, permit all requests to /api/v1/posts/**.

    // In your SecurityConfig's filterChain method, inside the http.authorizeHttpRequests() lambda:
    .requestMatchers("/api/v1/posts/**").permitAll()
    

    After restarting blog-service, send a POST request to http://localhost:8082/api/v1/posts with a request body like:

    {
        "title": "My First Post in the New Service",
        "content": "This is exciting!",
        "authorId": 1 
    }
    

    You should get a 201 Created response. Check your blog_content_db to confirm the post was saved with the correct author_id.


Debugging Task

A common issue when splitting services is a dependency-related startup failure.

Scenario: You run your auth-service, and it starts perfectly. You then run your blog-service, and the application fails to start with a NoSuchBeanDefinitionException related to your PostService. You check the console, and the error message says it cannot find a bean for UserRepository.

Question: Why would the blog-service be looking for a UserRepository? What mistake during the refactoring would cause this, and how would you fix it?

Click for the answer This error typically happens when a class was accidentally copied over or a dependency was left behind. In this case, it's likely that the `PostService` or another class in the `blog-service` still has an `@Autowired` field for `UserRepository` or `UserService`. During the "cut and paste" phase of migration, it's easy to miss these old, now-invalid dependencies. The fix is to find and remove the `@Autowired` injection of `UserRepository` from the `blog-service` codebase, as it has no business knowing about user persistence directly.

Conclusion

Congratulations! You have successfully performed a major architectural refactoring. You've taken a monolith and split it into two independent, deployable microservices. This is a foundational skill for building scalable, modern backend systems.

Key Takeaways:

  • Refactoring to microservices involves creating new, independent projects and migrating the relevant code.
  • The most critical step is decoupling, especially at the data layer. Direct entity relationships (@ManyToOne) across service boundaries must be replaced with simple ID references (Long authorId).
  • Each microservice is a full-fledged Spring Boot application that runs as a separate process, configured with its own port and database connection.

Preview of the Next Lesson:
We now have two services running independently, but this presents a new problem: how does a client application (like our Next.js frontend) talk to them? Making the client aware of every microservice's address is brittle and insecure. In the next lesson, we will solve this by introducing an API Gateway. We will use Spring Cloud Gateway to create a single entry point that intelligently routes incoming requests to the appropriate downstream service.