1 instantiation of constructor functions
2 instantiation of Static factory methods
3 Instance Factory method instantiation
Service Interface:
Package Service; Public Interface Personservice { publicvoid Save ();}
Personservicebean:
Package Service.impl; Import service. Personservice; Public class Implements Personservice { publicvoid Save () { System.out.println("I am Save () Method ");} }
Personservicebeanfactory:
PackageService.impl; Public classPersonservicebeanfactory {/** Static Factory method*/ Public StaticPersonservicebean Createpersonservicebean () {return NewPersonservicebean (); } /** Instance Factory method*/ PublicPersonservicebean createPersonServiceBean2 () {return NewPersonservicebean (); }}
Applicationcontext.xml
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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-3.1.xsd "> <!--default constructor Method - <BeanID= "Personservice"class= "Service.impl.PersonServiceBean"></Bean> <!--Static Factory mode - <BeanID= "PersonService2"class= "Service.impl.PersonServiceBeanFactory"Factory-method= "Createpersonservicebean"></Bean> <!--Instance Factory mode - <BeanID= "Personservicefactory"class= "Service.impl.PersonServiceBeanFactory"></Bean> <BeanID= "PersonService3"Factory-bean= "Personservicefactory"Factory-method= "CreatePersonServiceBean2"></Bean> </Beans>
Test class:
Packagetest;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importservice. Personservice;ImportService.impl.PersonServiceBean;/*** @ClassName: Firsttest * @Description: Test real Spring Three instantiation methods *@authorNameless * @date 2016-02-10*@version1.0*/ Public classfirsttest{@Test Public voidTestcreatebean () {String conf= "Applicationcontext.xml"; ApplicationContext AC=Newclasspathxmlapplicationcontext (conf); //using constructors to instantiatePersonservice PS = Ac.getbean ("Personservice", Personservicebean.class); Ps.save (); //using static factory methodsPersonservice PS02 = (personservice) ac.getbean ("PersonService2"); Ps02.save (); //Instance Factory methodPersonservice Ps03 = (personservice) ac.getbean ("PersonService3"); Ps03.save (); }}
Spring three ways of instantiating beans