Tuesday, 31 July 2018

What is Spring Dependency Injection with static Factory Method? - Playlist

Enjoying This Tutorial?

Subscribe to Ram N Java for high-quality, practical Java and Spring tutorials!

SUBSCRIBE NOW

Introduction

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.


Click here to watch on Youtube: 
https://www.youtube.com/watch?v=t8r-Xikrf6Y&list=PLmCsXDGbJHdiw40lKqmUAmFs753ZAnhhq

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • No comments:

    Post a Comment

    Tutorials