Spring Beans
What Is a Spring Bean?
A bean is an object managed by the Spring IoC container. Any class annotated with Spring stereotypes becomes a bean.
Bean Scopes
| Scope | Description | Use Case |
|---|---|---|
| singleton | One instance per container (default) | Stateless services |
| prototype | New instance each time | Stateful objects |
| request | One per HTTP request | Web apps |
| session | One per HTTP session | User sessions |
Bean Lifecycle
1. Container creates bean instance
2. Dependencies injected
3. BeanNameAware.setBeanName()
4. BeanFactoryAware.setBeanFactory()
5. ApplicationContextAware.setApplicationContext()
6. @PostConstruct
7. InitializingBean.afterPropertiesSet()
8. Custom init-method
9. Bean ready for use
10. @PreDestroy
11. DisposableBean.destroy()
12. Custom destroy-method
Bean Definition
@Component // Marks as Spring-managed bean
public class MyBean {
// Spring creates and manages this
}
@Configuration
public class AppConfig {
@Bean // Explicit bean definition
public MyBean myBean() {
return new MyBean();
}
}
Spring Best Practices
Configuration
- Use properties over YAML for simple configs
- Externalize configuration
- Use profiles for environments
- Validate on startup
Bean Management
- Prefer constructor injection
- Use appropriate scope
- Implement lazy initialization
- Clean up resources
Security
- Use Spring Security
- Implement CSRF protection
- Use method-level security
- Log security events
Key Points
- Understanding Spring Beans is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Spring Beans in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Spring Beans implementation
// Key aspects: validation, error handling, logging, testing
public class SpringBeans {
// Production-ready implementation
}Identify and handle edge cases for Spring Beans. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Spring Beans. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What is the default bean scope in Spring?
2. What method is called after dependencies are injected?
3. What is the primary purpose of Spring Beans?
4. What is a common mistake when implementing Spring Beans?
Flashcards
Question
What is a Spring bean?
Click to reveal answer
Answer
An object managed by the Spring IoC container
Question
Default bean scope?
Click to reveal answer
Answer
Singleton — one instance per container
Question
What is Spring Beans?
Click to reveal answer
Answer
Spring Beans is a key concept in backend development.
Question
When to use Spring Beans?
Click to reveal answer
Answer
Use Spring Beans when building production systems that require reliability, scalability, and maintainability.
Question
Spring Beans best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Bean = object managed by Spring IoC container
- 2.Default scope is singleton
- 3.Bean lifecycle: create -> inject -> init -> use -> destroy
- 4.@Component/@Service/@Repository/@Controller create beans
Interview Tips
- •Explain bean scopes and when to use each
- •Know the bean lifecycle
Cheat Sheet
Spring Beans
- Bean: Object managed by Spring IoC
- Scopes: singleton (default), prototype, request, session
- Lifecycle: create -> inject -> @PostConstruct -> use -> @PreDestroy
- Annotations: @Component, @Service, @Repository, @Controller