🌱 Spring Boot Q36 / 56

What is the difference between @Bean and @Component in Spring Boot?

AI-Powered Answer ✓ Answered

Both `@Bean` and `@Component` are fundamental annotations in Spring Boot for defining and managing beans within the Spring IoC container. While they both contribute to the bean lifecycle, they serve different purposes and are used in different contexts.

@Component

@Component is a class-level annotation that marks a Java class as a Spring-managed component. When Spring performs component scanning, it automatically detects classes annotated with @Component (and its specializations like @Service, @Repository, @Controller) and registers them as beans in the ApplicationContext. Spring takes care of their instantiation, dependency injection, and lifecycle management.

It's primarily used for classes that you write yourself and that form the core logic or layers of your application. Spring automatically creates a singleton instance of these components by default and can inject other dependencies into them.

java
@Component
public class MyService {
    public String greet() {
        return "Hello from MyService!";
    }
}

@Bean

@Bean is a method-level annotation. It is typically used within a @Configuration class (or other Spring-managed components) to explicitly declare a single bean definition. The method annotated with @Bean returns an instance of the object that Spring should register as a bean. This gives you fine-grained control over the instantiation, configuration, and dependencies of the bean.

It's commonly used for cases where you need to configure third-party libraries, complex objects, or when the bean's creation logic is more involved than a simple constructor call. You might also use it if you want to expose a specific instance of an object as a bean, rather than having Spring instantiate the class itself.

java
@Configuration
public class AppConfig {

    @Bean
    public DataSource myDataSource() {
        // Complex setup logic for a DataSource
        return new HikariDataSource(); // Example
    }

    @Bean
    public String appName() {
        return "My Spring Boot Application";
    }
}

Key Differences

Feature@Component@Bean
Usage LevelClass-levelMethod-level (typically within a @Configuration class)
Primary PurposeTo mark a class for auto-detection and registration as a Spring-managed bean.To explicitly declare a single bean instance and define its creation logic.
ControlLess direct control over bean instantiation (Spring handles it).Fine-grained control over bean instantiation, configuration, and dependencies.
External ClassesTypically for classes you write and have source code access to.Ideal for configuring third-party classes, complex objects, or specific interfaces where you don't control the source code.
InstantiationSpring scans for these components and instantiates them (e.g., via constructor).You write a method that explicitly returns the object instance that becomes the bean.
LocationCan be on any class.Methods within a `@Configuration` class (or any component-scanned class).
DependenciesDependencies are typically injected via `@Autowired` on fields or constructors.Dependencies can be passed as method parameters to the `@Bean` method.

When to use which?

  • Use @Component (or its specialized forms like @Service, @Repository, @Controller) when you are creating your own classes that represent a logical part of your application (e.g., services, data access objects, controllers). This is the most common approach for most application components.
  • Use @Bean when you need to explicitly configure a bean, especially for:
  • - Third-party classes where you don't have control over their source code (e.g., DataSource, RestTemplate, ObjectMapper).
  • - Conditional bean creation (e.g., @ConditionalOnProperty).
  • - Complex configuration that requires multiple steps or specific logic before the bean is ready.
  • - Exposing an instance of an interface where the concrete implementation is decided at runtime or requires specific parameters.

In essence, @Component is for classes you want Spring to manage automatically, while @Bean is for when you want to explicitly tell Spring how to create and configure a specific instance of an object.