What Is a Spring Bean?
A Spring bean is simply an object whose creation, configuration, and lifecycle are managed by the Spring IoC container instead of being created directly with the new keyword by application code. A class becomes a bean candidate when it is annotated with a stereotype annotation such as @Component, or when it is explicitly declared via a @Bean-annotated factory method inside a @Configuration class. Once registered, the bean is identified by a unique name (by default the class name with a lowercase first letter) inside the ApplicationContext's bean registry.
Cricket analogy: A player only appears on the official BCCI central contract list once selectors formally register them, just as a class only becomes a Spring bean once it's registered with the ApplicationContext, whether by @Component or a @Bean method.
Core Stereotype Annotations
Spring provides several stereotype annotations built on top of @Component that add semantic meaning: @Service marks a class holding business logic, @Repository marks a data-access class and additionally enables automatic translation of persistence exceptions into Spring's DataAccessException hierarchy, and @Controller (or @RestController, which combines @Controller and @ResponseBody) marks a class that handles HTTP requests. Functionally, all of these are treated as @Component by the container's classpath scanning, but the specific annotation communicates intent to other developers and unlocks annotation-specific framework behavior like exception translation for @Repository.
Cricket analogy: A team roster labels players as 'opener', 'all-rounder', or 'wicketkeeper' — all are still 'cricketers' but the label conveys role, just as @Service, @Repository, and @Controller are all @Component but signal a class's specific role.
@Repository
public class CustomerRepository {
private final JdbcTemplate jdbcTemplate;
public CustomerRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Customer findById(Long id) {
// SQLException is automatically translated to a DataAccessException subtype
return jdbcTemplate.queryForObject(
"SELECT * FROM customers WHERE id = ?", customerRowMapper(), id);
}
}
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public Customer getCustomer(Long id) {
return customerRepository.findById(id);
}
}
@RestController
@RequestMapping("/api/customers")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/{id}")
public Customer getCustomer(@PathVariable Long id) {
return customerService.getCustomer(id);
}
}Bean Lifecycle Annotations
Spring lets you hook into a bean's lifecycle using @PostConstruct, which runs immediately after dependency injection is complete and is commonly used to validate configuration or warm a cache, and @PreDestroy, which runs just before the container removes the bean from a singleton scope, typically used to release resources like closing a connection pool. For beans declared via @Bean methods, the same effect can be achieved with the initMethod and destroyMethod attributes of @Bean, which is useful for third-party classes you cannot annotate directly.
Cricket analogy: A player completes a mandatory fitness test right after being added to the squad, before playing a single match, similar to @PostConstruct running validation right after a bean's dependencies are injected but before it's used.
@PreDestroy is only guaranteed to run for singleton-scoped beans that the container fully manages through application shutdown. For prototype-scoped beans, Spring hands off the object after creation and does not track it further, so destruction callbacks are never invoked automatically — you must clean up prototype beans manually.
Qualifiers and the Primary Bean
When multiple beans implement the same interface, Spring cannot decide which one to inject by type alone and throws a NoUniqueBeanDefinitionException unless disambiguated. @Qualifier lets you inject a specific bean by its registered name at the injection point, while @Primary marks one implementation as the default choice whenever no explicit qualifier is given elsewhere. Choosing between them depends on intent: use @Primary for a genuinely 'default' implementation across the app, and @Qualifier when a specific injection point truly needs a non-default one.
Cricket analogy: When a team has three specialist spinners available, the captain must explicitly name which one bowls a given over rather than the ground staff guessing, just as @Qualifier explicitly picks a specific bean when several implement the same interface.
- A Spring bean is any object whose lifecycle is managed by the IoC container, registered via a stereotype annotation or a @Bean method.
- @Service, @Repository, and @Controller/@RestController are specialized forms of @Component that add semantic meaning and, for @Repository, exception translation.
- @PostConstruct runs after dependency injection completes; @PreDestroy runs before a singleton bean is destroyed.
- Prototype-scoped beans do not receive @PreDestroy callbacks because the container stops tracking them after creation.
- @Qualifier disambiguates which specific bean to inject when multiple candidates implement the same interface.
- @Primary designates a default bean implementation used whenever no explicit qualifier is specified.
- Third-party classes without annotation access can still use lifecycle hooks via @Bean(initMethod=..., destroyMethod=...).
Practice what you learned
1. What functional benefit does @Repository add beyond being a plain @Component?
2. When does @PostConstruct run relative to dependency injection?
3. Why doesn't @PreDestroy fire for prototype-scoped beans?
4. What is the purpose of @Qualifier?
5. How does @Primary differ from @Qualifier?
Was this page helpful?
You May Also Like
Dependency Injection Explained
Learn how Spring's IoC container supplies objects with the collaborators they need, instead of letting objects build those collaborators themselves.
Component Scanning
Learn how Spring discovers annotated classes on the classpath and registers them as beans, and how to control scan scope with filters.
Bean Scopes in Spring
Understand the difference between singleton, prototype, and web-aware bean scopes, and when scoped proxies are required.
Configuration Classes
Learn how @Configuration classes and @Bean methods provide explicit, programmatic bean wiring, and how to compose and conditionally activate them.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics