0
0
Spring Bootframework~30 mins

@Component annotation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Component Annotation in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that manages a greeting service. You want to create a reusable component that provides a greeting message.
🎯 Goal: Create a Spring Boot component using the @Component annotation and use it in the main application to display a greeting message.
📋 What You'll Learn
Create a class annotated with @Component
Define a method that returns a greeting string
Inject the component into the main application class
Call the greeting method and store the result in a variable
💡 Why This Matters
🌍 Real World
Spring Boot components are used to organize reusable parts of an application, like services or helpers, that can be injected where needed.
💼 Career
Understanding <code>@Component</code> and dependency injection is essential for building maintainable and testable Spring Boot applications, a common skill in Java backend development jobs.
Progress0 / 4 steps
1
Create a Greeting Component Class
Create a class called GreetingService and annotate it with @Component. Inside the class, create a method called getGreeting that returns the string "Hello, Spring!".
Spring Boot
Need a hint?

Use @Component above the class declaration to make it a Spring component.

2
Add a Field to Inject GreetingService
In the main application class called Application, add a private field of type GreetingService annotated with @Autowired to inject the component.
Spring Boot
Need a hint?

Use @Autowired to let Spring inject the GreetingService instance.

3
Call the Greeting Method
Inside the Application class, create a method called run that calls greetingService.getGreeting() and stores the result in a variable called message.
Spring Boot
Need a hint?

Call the method on the injected greetingService and save the result in message.

4
Add @SpringBootApplication and Run Method Call
Annotate the Application class with @SpringBootApplication. Inside the main method, create an ApplicationContext and get the Application bean. Then call the run method on it.
Spring Boot
Need a hint?

Use SpringApplication.run to start the app and get the Application bean from the context.