0
0
Spring Bootframework~30 mins

Constructor injection (preferred) in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor Injection in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that manages messages. You want to use constructor injection to provide a service to a controller. Constructor injection is the preferred way to inject dependencies in Spring Boot because it makes your code easier to test and more reliable.
🎯 Goal: Create a Spring Boot controller that uses constructor injection to get a message service. The controller will return a greeting message from the service.
📋 What You'll Learn
Create a service class called MessageService with a method getMessage() that returns a string.
Create a controller class called MessageController that uses constructor injection to get the MessageService.
The controller should have a method greet() that returns the message from the service.
Use Spring annotations @Service and @RestController appropriately.
💡 Why This Matters
🌍 Real World
Constructor injection is widely used in Spring Boot applications to manage dependencies cleanly and make components easier to test and maintain.
💼 Career
Understanding constructor injection is essential for Java developers working with Spring Boot, as it is the preferred way to inject dependencies in professional projects.
Progress0 / 4 steps
1
Create the MessageService class
Create a class called MessageService annotated with @Service. Inside it, create a method called getMessage() that returns the string "Hello from MessageService!".
Spring Boot
Need a hint?

Use @Service above the class. Define getMessage() to return the exact string.

2
Create the MessageController class with constructor
Create a class called MessageController annotated with @RestController. Add a private final field of type MessageService called messageService. Create a public constructor that takes a MessageService parameter called messageService and assigns it to the field.
Spring Boot
Need a hint?

Use @RestController above the class. Declare the field as private final. Create a constructor that assigns the parameter to the field.

3
Add the greet() method to MessageController
Inside MessageController, add a public method called greet() that returns a String. This method should return the result of calling getMessage() on the messageService field.
Spring Boot
Need a hint?

Define greet() to call getMessage() on the injected service and return its result.

4
Add @GetMapping to greet() method
Add the annotation @GetMapping("/greet") above the greet() method in MessageController so it handles HTTP GET requests at the path /greet.
Spring Boot
Need a hint?

Use @GetMapping("/greet") just above the greet() method.