0
0
Spring Bootframework~5 mins

@Component annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @Component annotation tells Spring to create and manage an object automatically. It helps you avoid writing extra code to make objects yourself.

When you want Spring to create and manage a simple class as a reusable object.
When you have a helper class that other parts of your app need to use.
When you want to organize your code so Spring can find and use your classes easily.
Syntax
Spring Boot
@Component
public class MyClass {
    // class body
}

Place @Component above the class declaration.

Spring will create one instance (singleton) by default.

Examples
This class will be managed by Spring and can be used anywhere by injecting it.
Spring Boot
@Component
public class ServiceHelper {
    public void help() {
        System.out.println("Helping...");
    }
}
You can give a custom name to the component for easier reference.
Spring Boot
@Component("customName")
public class CustomComponent {
    // class body
}
Sample Program

This example shows two classes marked with @Component. Spring creates and connects them automatically. The UserController uses GreetingService to print a greeting.

Spring Boot
import org.springframework.stereotype.Component;

@Component
public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserController {
    private final GreetingService greetingService;

    @Autowired
    public UserController(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    public void sayHello() {
        System.out.println(greetingService.greet("Alice"));
    }
}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        var context = new AnnotationConfigApplicationContext("your.package.name");
        UserController userController = context.getBean(UserController.class);
        userController.sayHello();
        context.close();
    }
}
OutputSuccess
Important Notes

Spring creates only one instance of a @Component class by default (singleton).

Use @Autowired to let Spring connect components automatically.

Make sure your package is scanned by Spring to find @Component classes.

Summary

@Component marks a class for Spring to manage automatically.

It helps connect parts of your app without manual object creation.

Use @Autowired to inject these components where needed.