Welcome back! In our last lesson, we successfully created our first REST controller and defined endpoints using @GetMapping and @PostMapping. You saw how closely these concepts map to the route handlers you're familiar with in Express.js. Our controller, however, currently holds the data it serves, which is not a sustainable practice.
Today, we'll take a critical step towards a professional application architecture. This lesson addresses the learning outcome: Implement a service layer to contain business logic and inject it into the controller.
We will refactor our application to introduce a "Service" layer. This is where the core business logic of your application will live. This separation of concerns is a cornerstone of maintainable and scalable backend systems. You'll also get your first hands-on experience with one of Spring's most powerful features: Dependency Injection (DI).
1. The "Fat Controller" Problem and the Service Layer Solution
In our previous lesson, our BlogController looked like this:
@RestController
public class BlogController {
@GetMapping("/api/posts")
public List<String> getAllPosts() {
// Business logic is here!
return List.of("My First Blog Post", "Learning Spring Boot");
}
}
This is what's often called a "Fat Controller". The controller is doing more than it should; it's handling both HTTP request/response duties and business logic.
Why is this a problem?
- Poor Reusability: What if a scheduled job also needs to get all posts? It would have to duplicate this logic.
- Difficult to Test: To unit test the controller, you're forced to also test the business logic within it, making tests brittle and complex.
- Violates Separation of Concerns (SoC): The controller's single responsibility should be managing HTTP interactions.
The solution is the Service Layer. Think of it as the "brain" of your application.

To understand the role and benefits of the service layer more deeply, let's start with a quick read.
Service Layer Pattern in Java With Spring Boot
The article 'Service Layer Pattern in Java With Spring Boot' from Foojay.io provides an excellent conceptual foundation for what we're about to build.
Please read the sections titled 'What is the Service Layer pattern?', 'Why use a service layer?', and 'How the Service Layer fits with MVC'. Focus on understanding why this separation is crucial for building robust applications.
2. MERN Comparison: Services in Node.js vs. Spring
In a well-structured MERN application, you've likely already used a similar pattern. You might have a posts.controller.js that calls functions from a posts.service.js:
Express.js Example:
// posts.controller.js
const postService = require('../services/posts.service');
const getAllPosts = (req, res) => {
const posts = postService.findAll(); // Delegate to service
res.json(posts);
};
Here, the controller requires the service. The key difference in Spring is Inversion of Control (IoC). Instead of the controller creating or fetching its dependencies, the Spring framework provides them. This is done through Dependency Injection (DI).

3. Implementing the Service and Injecting it
Let's refactor our application to use a service layer and DI.
Step 1: Create the BlogService Class
-
In your project, create a new package named
serviceat the same level as yourcontrollerpackage. -
Inside the
servicepackage, create a new Java class namedBlogService. -
Add the
@Serviceannotation to the class. This annotation tells Spring, "Create an instance of this class and manage it in your IoC container. It is a 'bean' that can be injected elsewhere."package com.blogplatform.service; import org.springframework.stereotype.Service; import java.util.List; @Service public class BlogService { public List<String> getAllPosts() { // This is now our business logic layer. return List.of("My First Blog Post (from Service)", "Learning Spring Boot (from Service)"); } }
@Service is a specialized version of the more general @Component annotation. It adds no extra behavior but serves as a stereotype, making the code easier to read and understand for developers.
Step 2: The Problem with Manual Instantiation
You might be tempted to use this new service in your controller like this:
// BlogController.java - DON'T DO THIS
public class BlogController {
private BlogService blogService = new BlogService(); // Manual instantiation
// ...
}
This is tight coupling. The BlogController is now directly responsible for creating its BlogService dependency. This leads to the same testability problems we wanted to solve. The following video explains this anti-pattern and its consequences perfectly.
Dependency Injection Spring: How to use Dependency Injection in Spring Boot
The video 'Dependency Injection Spring' by Dan Vega brilliantly demonstrates why manually creating dependencies inside a class is a bad idea, especially when it comes to testing.
Watch from 04:33 to 09:40, where the presenter manually creates a repository in a controller. Then, pay close attention to the segment from 11:31 to 15:58, where he shows how this makes proper unit testing impossible, accidentally creating an integration test instead.
Step 3: Inject the BlogService using Constructor Injection
Now, let's do it the "Spring way". We will use constructor injection, which is the recommended method for injecting dependencies.
Modify your BlogController.java as follows:
package com.blogplatform.controller;
import com.blogplatform.service.BlogService; // Import the service
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class BlogController {
// 1. Declare the dependency as a private final field.
// 'final' ensures it's immutable after construction.
private final BlogService blogService;
// 2. Create a constructor that accepts the dependency.
// Spring will automatically 'inject' the BlogService bean here.
public BlogController(BlogService blogService) {
this.blogService = blogService;
}
@GetMapping("/api/posts")
public List<String> getAllPosts() {
// 3. Delegate the call to the service. The controller is now 'thin'.
return blogService.getAllPosts();
}
@PostMapping("/api/posts")
public String createPost() {
// We will move this to the service later.
return "Post created successfully!";
}
}
What just happened?
- When Spring starts, it scans your code for annotations like
@Serviceand creates instances of those classes (beans). - It then sees that
BlogController(which is also a bean, thanks to@RestController) has a constructor that requires aBlogServiceinstance. - Spring finds the
BlogServicebean it already created and passes it into theBlogController's constructor.
This is DI in action! Note that because BlogController has only one constructor, the @Autowired annotation is optional and generally omitted for cleaner code.
4. Why Constructor Injection is Recommended
There are other ways to do DI (field injection, setter injection), but constructor injection is the standard for modern Spring applications. Let's watch a video that explains why.
Spring Constructor Injection: Why is it the recommended approach to Dependency Injection?
In this video, 'Spring Constructor Injection', Dan Vega explains the different types of DI and makes a strong case for why constructor injection is superior, focusing on immutability and testability.
Watch from 17:05 to 19:12 to see constructor injection in action. Then, continue watching from 19:12 to 24:35 for a critical analysis of the other methods (setter and field injection) and why they are discouraged.
5. Debugging Task: See DI at Runtime
To truly understand that the framework is doing the work, let's observe it.
- In your
BlogController.java, place a breakpoint on the line inside the constructor:this.blogService = blogService;. - Run your application in Debug Mode.
- The application will pause at your breakpoint during startup.
- Hover your mouse over the
blogServiceparameter in the constructor. You will see that it is a fully instantiated object, notnull. Its ID will look something likeBlogService@1234. This instance was created and provided by the Spring IoC container.
This simple exercise confirms that you are no longer responsible for object creation; you simply declare your dependencies, and Spring wires them together.
After observing, resume the program. Test your endpoint again with curl http://localhost:8080/api/posts. You should now see the response coming from your service.
Conclusion
Fantastic work! You have successfully implemented one of the most important patterns in backend development. By separating concerns, you've made your code cleaner, more testable, and more reusable.
Key Takeaways:
- The Service Layer is where your application's business logic should reside, keeping controllers "thin" and focused on HTTP concerns.
- Inversion of Control (IoC) is a principle where the framework manages object lifecycles and dependencies, rather than your own code.
- Dependency Injection (DI) is the mechanism by which IoC is achieved. Spring "injects" dependencies (beans) into the classes that need them.
@Serviceis used to declare a class as a service bean for the IoC container to manage.- Constructor Injection with
private finalfields is the recommended, modern approach for DI in Spring, as it guarantees immutability and clearly states a class's required dependencies.
Preview of the Next Lesson:
Our getAllPosts() method still returns a simple List<String>. In a real API, you would want to return structured data. In the next lesson, we will define Data Transfer Objects (DTOs) to create a stable API contract separate from internal domain models. This is another crucial step in building a professional-grade REST API.