Spring-boot读书笔记一@Component.vs.@bean

Spring-boot读书笔记一@Component.vs.@bean

Component vs Bean in Spring Boot

Both are Spring-managed objects, but they differ in how and where they're defined.

@Component
Class-level annotation - marks the class itself as a Spring component

@Component
public class UserService {public void saveUser(String name) {// business logic}
}

Characteristics:

  • Applied directly to the class
  • Spring auto-detects during component scanning
  • One instance per class (unless specified otherwise)
  • Class controls its own creation

@Bean
Method-level annotation - creates beans through factory methods in @Configuration classes

@Configuration
public class AppConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}@Beanpublic DatabaseService databaseService() {return new DatabaseService("localhost", 5432);}
}

Characteristics:

  • Applied to methods in @Configuration classes
  • You control object creation and configuration
  • Can create multiple beans from same class
  • External configuration of third-party classes

Key Differences
@Component @Bean
Class-level Method-level
Auto-detected Explicitly defined
Own classes Any classes (including third-party)
Simple creation Custom creation logic
One bean per class Multiple beans possible

When to Use Each

  • @Component for:

    1. Your own business classes
    2. Services, repositories, controllers
    3. Simple object creation
  • @Bean for:

    1. Third-party library objects
    2. Complex object configuration
    3. Conditional bean creation
    4. Multiple instances of same class

Both @Component and @Bean result in Spring-managed objects, but @Bean gives more control over the creation process.