Drop Down

Saturday, September 21, 2019

Spring_App_8.3_BeanLifeCycleUsingStaticFactoryMethod

package com.amit.bean;

public class HelloBean
{

private HelloBean()    // here private method is getting accessed due to Reflection
{
System.out.println("Constructor: Bean Object Creating...");
}

public static HelloBean getInstance()  //---getInstance()  (use it in config file)
{
System.out.println("Bean instantiation through static factory method");
return new HelloBean();
}
public String sayHello()
{
return "Hello User";
}

}
=====================================================================
package com.amit.test;

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

import com.amit.bean.HelloBean;

public class Test {

public static void main(String[] args) 
{
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  HelloBean b = (HelloBean)context.getBean("helloamit");
  System.out.println(b.sayHello());

}

}
====================================================================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--  <bean id="helloamit" class="com.amit.bean.HelloBean"/>   --> <!-- Use this for normal instantiation -->
<bean id="helloamit" class="com.amit.bean.HelloBean" factory-method="getInstance"/>   <!-- Use this for static factory method -->
</beans>        

No comments:

Post a Comment

Java 8 Notes Pics