Q1. What is a Spring bean?
A Spring bean is an object that is instantiated, assembled, and managed by the Spring IoC container.
Beans are defined in configuration metadata (XML, annotations, or Java config) and form the backbone of a Spring application.
They can be any POJO class.
Beans are defined in configuration metadata (XML, annotations, or Java config) and form the backbone of a Spring application.
They can be any POJO class.
Q2. Explain the Spring bean lifecycle.
The bean lifecycle consists of:
• instantiation (container creates bean)
• population of properties (dependency injection)
• setting bean name and bean factory
• pre-initialization (BeanPostProcessor before)
• afterPropertiesSet (if bean implements InitializingBean)
• custom init method
• post-initialization (BeanPostProcessor after)
• bean ready for use
• destruction (DisposableBean or custom destroy method)
• instantiation (container creates bean)
• population of properties (dependency injection)
• setting bean name and bean factory
• pre-initialization (BeanPostProcessor before)
• afterPropertiesSet (if bean implements InitializingBean)
• custom init method
• post-initialization (BeanPostProcessor after)
• bean ready for use
• destruction (DisposableBean or custom destroy method)
Q3. How can you define custom initialization and destroy methods?
You can specify custom init and destroy methods using:
• annotations
• implementing
• configuring
Example:
• annotations
@PostConstruct and @PreDestroy• implementing
InitializingBean and DisposableBean interfaces• configuring
init-method and destroy-method in XML/Java configExample:
@Bean(initMethod = "init", destroyMethod = "cleanup")
public MyBean myBean() { return new MyBean(); }
Q4. What are BeanPostProcessors?
BeanPostProcessors are special interfaces that allow custom modification of new bean instances before and after initialization.
They can process beans after they are created but before they are put into use.
They are commonly used for wrapping beans with proxies, checking marker interfaces, etc.
They can process beans after they are created but before they are put into use.
They are commonly used for wrapping beans with proxies, checking marker interfaces, etc.
Q5. How does Spring manage bean lifecycles in a web application?
In a web application, Spring's
Beans are created and initialized as per their scopes (singleton, prototype, etc.).
The container shuts down when the application is undeployed, triggering destroy methods for singleton beans.
ApplicationContext is typically loaded at startup (via ContextLoaderListener).Beans are created and initialized as per their scopes (singleton, prototype, etc.).
The container shuts down when the application is undeployed, triggering destroy methods for singleton beans.
