Spring Beans and Beans Life Cycles-interview
Q1. What is a Spring Beans ?
A Spring Bean is any Java object that is created, managed and destroyed by the Spring IoC Container.
Spring handles:
Spring creates it automatically and gievs it to you whenever needed.
Spring handles:
- Creatating the object
- Injection its required dependencies
- Running initialization logic
- Destroying the object when the application stops
- So instead of you manually doing
MyService service = new MyService();Spring creates it automatically and gievs it to you whenever needed.
Q2. How do you declare a Spring Bean ?
The most common way is by using stereotype annotations:
- @Component
- @Service
- @Repository
- @Controller
Example
Spring automatically detects these calsses during coponent scanning and crates their bean objects.
@Componentpublic class MyService {}Spring automatically detects these calsses during coponent scanning and crates their bean objects.
Q3. How does Spring create beans internally ?
Spring uses Componenet Scanning.
When the application starts:
Example configuration
When the application starts:
- It scans the given package.
- Finds classes with @Component ( and related annotations).
- Creates bean objects.
- Injects dependencies.
- Stores them inside the IoC Container for later use.
Example configuration
@Configuration@ComponentScan("com.example")public class AppConfig {}Q4. What are Spring Beans Scopes ? Explain each.
A bean scope defines how many instances of a bean Spring creates.
1. Singleton (Default)
2. Prototype
3. Request (Web apps)
4. Session
5. Applicatoin
1. Singleton (Default)
- Only one instance in the entire application.
- Used 90% of the time.
@Scope("singleton")2. Prototype
- A new instance every time the bean is requested.
@Scope("prototype")3. Request (Web apps)
- One instance per HTTP request
@Scope("request")4. Session
- One instance per user session
@Scope("session")5. Applicatoin
- One instance per servlet context.
Q5. What is the Spring Bean Lifecycle ?
The bean lifecycle describes how Spring manages a bean from creation --> usage --> destruction.
Full lifecycle:
1. Instantiation
2. Dependency Injection
3. Initialization
Code inside:
4. Bean Ready
5. Destruction
Cleanup code runs:
Full lifecycle:
1. Instantiation
- Spring calls the constructor and creates the object.
2. Dependency Injection
- Spring injects required dependencies (via constructor, setter or field).
3. Initialization
Code inside:
- @PostConstruct
- afterPropertiesSet() (InitializingBean)
- custom initMethod
4. Bean Ready
- Bean is ready to be used by the application.
5. Destruction
Cleanup code runs:
- @PreDestroy
- destroy() (DisposableBean)
- custom destroy method