Knowledge Point Introduction:
The instance factory means that the method that gets the object instance is not static, so you need to first new factory class and then call the normal instance method.
"Reproduced use, please specify the source: http://blog.csdn.net/mahoking "
Operation Steps:
1. Create a Speaker object.
public class Speaker {//Use instance factory method to instantiate Beanprivate string Speakername;public Speaker (string speakername) {This.speakername = Speakername;} /** * Lecture */public void speech () {System.out.println (toString ());} @Overridepublic String toString () {return "Speaker [speakername=" + Speakername + "]";}}
2. Create a Speakerfactory object.
public class Speakerfactory {/** * Factory method * @param speakername * @return */public Speaker newinstance () {String speakername = "Lucy and Lily"; return new Speaker (Speakername);}}
3. Create a spring configuration file, Beanlearn04.xml.
<?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/ Beanshttp://www.springframework.org/schema/beans/spring-beans.xsd "><!--learn 04 Instantiate beans using the instance factory method--><! --Define instance factory bean--><bean id= "speakerfactory" class= "Com.mahaochen.spring.learn04.SpeakerFactory"/><!-- Use instance factory bean to create bean--><bean id= "speaker04" class= "Com.mahaochen.spring.learn04.Speaker" factory-bean= " Speakerfactory "factory-method=" newinstance "></bean></beans>
4. Introduce the spring configuration file beanlearn04.xml into the master profile Beans.xml.
<!--learn instantiate bean--><import resource= "Com/mahaochen/spring/learn04/beanlearn04.xml"/> Using the Instance factory method
5, write test class Testspring04.java.
public class TestSpring04 {public static void main (string[] args) {beanfactory beanfactory = new Classpathxmlapplicationco ntext ("beans.xml");//Instantiate Beanspeaker speaker04 = Beanfactory.getbean ("Speaker04", Speaker.class) using the instance factory method; Speaker04.speech ();}}
"Reproduced use, please specify the source: http://blog.csdn.net/mahoking "
Spring instantiates beans using instance factory methods