@Bean vs @Component in Spring

1. Introduction

In Spring, one of the core features is Dependency Injection (DI), which can be managed with annotations like @Bean and @Component. @Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically. It decouples the definition of the bean from the class definition. @Component is used to auto-detect and auto-configure beans using classpath scanning.

2. Key Points

1. @Bean is a method-level annotation that marks a method to create and return a bean.

2. @Component is a class-level annotation that tells Spring to treat the class as a bean.

3. @Bean is usually declared in Configuration classes methods.

4. @Component is typically used when you don't need to add any extra logic to create the bean.

3. Differences

@Bean @Component
Defines a bean in a Java configuration file. Marks a class as a Spring component.
You have control over the instantiation process. Spring framework automatically instantiates the class.
Allows for complex logic during bean instantiation. Straightforward approach suitable for simple beans without complex creation logic.

4. Example

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        // You can control the creation of the bean here
        return new MyBean();
    }
}

@Component
public class MyComponent {
    // Spring will automatically create a bean of type MyComponent
}

public class MyBean {
    // Bean content here
}

Output:

// No output, since this is about the configuration, not about running the application

Explanation:

1. The AppConfig class uses @Bean to create a bean of type MyBean. You can add custom creation logic in the myBean method if needed.

2. The MyComponent class is annotated with @Component, which allows Spring to automatically pick it up and create a bean instance without any additional configuration.

5. When to use?

- Use @Bean for any complex or third-party classes that you need to integrate into your Spring application, where you need to control the creation of the object.

- Use @Component for your own classes to simplify the automatic detection and configuration of your Spring beans.

Comments