Q1. What is a factory method in Spring?
A factory method is a method that creates and returns an object instance.
In Spring, you can define beans that are created by factory methods instead of constructors.
This is useful when you need to integrate with legacy code or when object creation involves complex logic.
In Spring, you can define beans that are created by factory methods instead of constructors.
This is useful when you need to integrate with legacy code or when object creation involves complex logic.
Q2. How do you define a bean using a static factory method?
In XML, you use the
Example:
factory-method attribute.Example:
<bean id="clientService" class="com.example.ClientService" factory-method="createInstance"/>
In Java config, you can simply call the factory method in a @Bean method.Q3. What is an instance factory method?
An instance factory method is a non-static method of a factory bean that creates another bean.
You need to define the factory bean first, then use
Example:
You need to define the factory bean first, then use
factory-bean and factory-method attributes.Example:
<bean id="factory" class="com.example.MyFactory"/>
<bean id="myBean" factory-bean="factory" factory-method="getInstance"/>
Q4. How do you pass arguments to a factory method?
In XML, you use
For static factory methods, arguments are passed to the method.
For instance factory methods, arguments are also passed via
<constructor-arg> inside the bean definition to pass arguments to the factory method.For static factory methods, arguments are passed to the method.
For instance factory methods, arguments are also passed via
constructor-arg elements.Q5. What is the FactoryBean interface in Spring?
Beans implementing
The container uses
This is used for complex object creation like proxying, etc.
FactoryBean is an interface that allows you to customize the bean creation logic.Beans implementing
FactoryBean can produce objects of a different type.The container uses
getObject() to obtain the actual bean.This is used for complex object creation like proxying, etc.
