Spring 面试题, Spring 中的 ObjectFactory 是什么?
Spring 面试题, Spring 中的 ObjectFactory 是什么?
QA
Step 1
Q:: What is ObjectFactory in Spring?
A:: ObjectFactory is a functional interface in Spring Framework, which is a part of the core container. It provides an abstraction for obtaining an instance of an object. The getObject() method of ObjectFactory is used to retrieve an instance of the object managed by the Spring container. ObjectFactory is often used in situations where you need a new instance of a prototype bean each time it's required, avoiding the overhead of a bean lookup from the container.
Step 2
Q:: How is ObjectFactory different from FactoryBean?
A:: While both ObjectFactory and FactoryBean are used to create objects in Spring, they serve different purposes. ObjectFactory is a simple factory interface that allows for deferred retrieval of bean instances, while FactoryBean is a more complex interface used to create objects that are themselves managed as beans within the Spring container. FactoryBean can be used to customize the instantiation logic of a bean, whereas ObjectFactory is more lightweight and generally used for prototype beans.
Step 3
Q:: In what scenarios should ObjectFactory be used?
A:: ObjectFactory is particularly useful in situations where you have a prototype bean, but you need to delay its instantiation until it's absolutely necessary. It can also be used to avoid circular dependencies by not instantiating beans until they are needed.
Step 4
Q:: How do you inject ObjectFactory in Spring?
A:: ObjectFactory can be injected into a Spring bean using the @Autowired annotation. Spring will automatically wire the ObjectFactory for the specified bean type. This allows the bean to request instances from the factory whenever needed, thus ensuring that the bean instance is only created when it is used.
Step 5
Q:: What is the difference between Singleton and Prototype scope in Spring?
A:: In Spring, Singleton scope means that a single instance of the bean is created and shared across the entire Spring container, while Prototype scope means that a new instance of the bean is created every time it is requested from the container. ObjectFactory is often used with Prototype scope beans to manage their instantiation.