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 {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public 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:
- Your own business classes
- Services, repositories, controllers
- Simple object creation
-
@Bean for:
- Third-party library objects
- Complex object configuration
- Conditional bean creation
- Multiple instances of same class
Both @Component and @Bean result in Spring-managed objects, but @Bean gives more control over the creation process.

浙公网安备 33010602011771号