Spring DI (factory method)

Now that we understand the Spring Dependency Injection and the singleton implementation, and we also know how to configured the class as bean in spring definition file which has the constructor either the default or overridden. Let’s understand how to configure the singleton class in spring.
To highlight the scenario singleton does not have a public constructor (which means new keyword cannot be used to instantiate the object of this class) and has a public static getInstance method to get the instance of the class.
Spring provided the way to configure such classes as beans through the factory methods. Here we will configure the factory-method which is responsible to return the object of the class.

The singleton class would be


The singleton I read in the "Spring in Action" book
package test.patterns;

public class SingltonInner {

  private SingltonInner(){}
  
  private static class InnerSingltonInstance{
    static SingltonInner singlton = new SingltonInner();
  }
  
  public static SingltonInner getInstance(){
    return InnerSingltonInstance.singlton;
  }
  
  public String getMessage(String name){
    return "Hello " + name;
  }
}

Java2html

The class using the Singleton

package test.spring.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.patterns.SingltonInner;

public class FactoryInjection {
  
  private SingltonInner singleton = null;
  
  public SingltonInner getSingleton() {
    return singleton;
  }

  public void setSingleton(SingltonInner singleton) {
    this.singleton = singleton;
  }
public public static void main(String arg[]){
        ApplicationContext ctx_1 = new ClassPathXmlApplicationContext("test//spring//injection//factory-injection.xml");
        FactoryInjection fInjection =(FactoryInjectionctx_1.getBean("factoryInjection");    
        System.out.println("Calling the singleton method :"+fInjection.singleton.getMessage("Java Om"));    
  }
}
Java2html


The definition of the beans is in this XML file.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="factoryInjection" class="test.spring.injection.FactoryInjection">
        <property name="singleton">
            <ref bean="singltonInner"/>
        </property>
    </bean>
    <bean id="singltonInner" class="test.patterns.SingltonInner" factory-method="getInstance"/>
</beans>

No comments:

Followers