Spring Boot @Bean vs. @Component | Key Differences & When to Use Them

🚀 Introduction: What’s the Difference?

In Spring Boot, both @Bean and @Component are used to define beans in the Spring ApplicationContext. However, their usage and behavior are different.

📌 Quick Summary:
@Bean is used in manual bean configuration inside a @Configuration class.
@Component is used for automatic component scanning and dependency injection.

🚀 So, when should you use @Bean vs. @Component? Let’s break it down!

1️⃣ What is @Component? (Automatic Bean Registration)

The @Component annotation automatically registers a class as a Spring bean.

✅ Example: Using @Component to Register a Bean

@Component
public class UserService {
    public String getUser() {
        return "John Doe";
    }
}

Spring automatically detects this bean and registers it in the application context.

🔹 @Component with Stereotype Annotations

@Component is the parent annotation for other specialized stereotypes:

Annotation Purpose
@Service Marks a service layer component.
@Repository Marks a repository (DAO) component.
@Controller Marks a Spring MVC controller.
@RestController A specialized @Controller for REST APIs.

Example: Using @Service (which is a @Component)

@Service
public class OrderService {
    public String processOrder() {
        return "Order processed!";
    }
}

Spring automatically registers this service bean.

2️⃣ What is @Bean? (Manual Bean Registration)

The @Bean annotation manually defines a Spring bean inside a @Configuration class.

✅ Example: Using @Bean in a @Configuration Class

@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}

Here, we explicitly create a UserService bean instead of relying on Spring’s component scanning.

3️⃣ Automatic Dependency Injection (@Component) vs. Manual Injection (@Bean)

Using @Component for Automatic Dependency Injection

@Component public class EmailService { public void sendEmail(String message) { System.out.println("Email sent: " + message); } } @Service public class NotificationService { private final EmailService emailService; public NotificationService(EmailService emailService) { this.emailService = emailService; } public void notifyUser() { emailService.sendEmail("Welcome to our app!"); } }

Spring automatically injects EmailService into NotificationService.

Using @Bean for Manual Dependency Injection

@Configuration public class AppConfig { @Bean public UserRepository userRepository() { return new UserRepository(); } @Bean public UserService userService(UserRepository userRepository) { return new UserService(userRepository); } }

Spring explicitly injects UserRepository into UserService via method parameters.

4️⃣ @Bean vs. @Component – Key Differences

Feature @Bean @Component
Definition Used in @Configuration classes Used on classes directly
Bean Creation Manual bean definition Automatic component scanning
Flexibility Can return third-party beans Only works with Spring-managed classes
Dependencies Allows passing constructor arguments Uses dependency injection
When to Use? When configuring third-party libraries or beans When defining standard application components

🚀 Best Practice:
✔ Use @Component for most cases (services, repositories, controllers).
✔ Use @Bean when you need manual bean configuration (e.g., third-party beans, external libraries).

5️⃣ When Should You Use @Bean? (Real-World Examples)

🔹 1. Registering a Third-Party Library as a Spring Bean

If you need to create a Spring bean for a third-party class, use @Bean.

@Configuration
public class AppConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}

✅ Here, ObjectMapper (Jackson) is not a Spring component, so we manually register it.

🔹 2. Configuring Multiple Bean Instances

With @Bean, you can create multiple beans of the same type with different configurations.

@Configuration
public class AppConfig {

    @Bean(name = "devDataSource")
    public DataSource devDataSource() {
        return new DataSource("jdbc:mysql://localhost/devdb");
    }

    @Bean(name = "prodDataSource")
    public DataSource prodDataSource() {
        return new DataSource("jdbc:mysql://localhost/proddb");
    }
}

Here, we define two DataSource beans with different configurations.

6️⃣ When Should You Use @Component? (Real-World Examples)

🔹 1. Automatic Dependency Injection

Use @Component when you want Spring to handle dependency injection automatically.

@Component
public class EmailService {
    public void sendEmail(String message) {
        System.out.println("Email sent: " + message);
    }
}

@Service
public class NotificationService {

    private final EmailService emailService;

    public NotificationService(EmailService emailService) {
        this.emailService = emailService;
    }

    public void notifyUser() {
        emailService.sendEmail("Welcome to our app!");
    }
}

Spring automatically injects EmailService into NotificationService.

7️⃣ Can @Bean and @Component Work Together?

Yes! You can mix both annotations when needed.

✅ Example: Using @Bean and @Component Together

@Component
public class UserRepository {
    public String getUser() {
        return "John Doe";
    }
}

@Configuration
public class AppConfig {

    private final UserRepository userRepository;

    public AppConfig(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Bean
    public UserService userService() {
        return new UserService(userRepository);
    }
}

Spring injects UserRepository into UserService even though UserService is manually configured!

@ComponentScan – How Spring Finds @Component Beans

Spring Boot automatically scans components in the same package as the main application class.

@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

@ComponentScan tells Spring where to look for @Component beans.

🎯 Conclusion: When to Use @Bean vs. @Component?

✔ Use @Component for standard Spring beans (services, repositories, controllers).
✔ Use @Bean for third-party beans, external libraries, or advanced configurations.

🚀 Still have questions? Comment below!

🔗 Bookmark this guide for future reference! 🚀

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare