Enjoying This Tutorial?
Subscribe to Ram N Java for high-quality, practical Java and Spring tutorials!
SUBSCRIBE NOWIntroduction
In Spring, the IoC container typically instantiates beans by calling their public constructors directly. However, in enterprise applications and legacy integrations, objects are often created through static factory methods. Spring provides built-in support for static factory instantiation using the factory-method attribute in XML configuration.
Why Use Static Factory Methods in Spring?
- Legacy & Third-Party Library Integration: Allows seamless management of existing classes that restrict constructor access in favor of static creator methods.
- Centralized Instantiation Logic: Encapsulates complex creation logic, object reuse, or pre-configuration within the factory method.
- Full Dependency Injection Support: Spring can pass arguments directly into the static factory method using standard
<constructor-arg>elements.
Step-by-Step Configuration Example
Suppose you have a service class with a private constructor and a static factory method:
1. The Java Class with Static Factory Method
package com.ram.service;
public class OrderService {
private OrderService() {}
public static OrderService createInstance() {
return new OrderService();
}
public void serve() {
System.out.println("Order service executed successfully.");
}
}
2. XML Configuration with factory-method
<bean id="orderService"
class="com.ram.service.OrderService"
factory-method="createInstance" />
3. Loading the Bean via ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
OrderService service = (OrderService) context.getBean("orderService");
service.serve();
Key Takeaway
Specifying factory-method instructs Spring's IoC container to invoke the static method on the specified class rather than invoking a constructor. This makes integrating non-standard or legacy factories into your Spring context clean and effortless.
Recommended Spring Tutorials from Ram N Java
Click here to watch on Youtube:
https://www.youtube.com/watch?v=t8r-Xikrf6Y&list=PLmCsXDGbJHdiw40lKqmUAmFs753ZAnhhq
See also:
No comments:
Post a Comment