Loading

Quipoin Menu

Learn • Practice • Grow

spring / Factory Method in Spring
interview

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.

Q2. How do you define a bean using a static factory method?
In XML, you use the factory-method attribute. Example:
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 factory-bean and factory-method attributes. Example:

Q4. How do you pass arguments to a factory method?
In XML, you use 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?
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.