實例化過程如圖,方式如圖。html
甩代碼。spring
方式一:構造方法app
搞一個bean,修改一下xml配置測試
package com.itheima.instance.constructor; public class Bean1 { public Bean1(){ System.out.println("bean1 實例化"); } }
<bean id = "bean1" class = "com.itheima.instance.constructor.Bean1"/>
方式二:靜態工廠方法調用xml
package com.itheima.instance.static_factory; public class MyBean2Factory { public MyBean2Factory(){ System.out.println("bean2Factory 實例化中"); } public static Bean2 createBean(){ return new Bean2(); } }
package com.itheima.instance.static_factory; public class Bean2 { public Bean2(){ System.out.println("bean2 實例化"); } }
<bean id ="bean2" class = "com.itheima.instance.static_factory.MyBean2Factory" factory-method = "createBean"></bean>
方式三:實例化工廠,調用工廠實例的方法htm
package com.itheima.instance.factory; public class MyBean3Factory { public MyBean3Factory(){ System.out.println("bean3工廠實例化中"); } public Bean3 createBean(){ return new Bean3(); } }
package com.itheima.instance.factory; public class Bean3 { public Bean3(){ System.out.println("bean3 實例化"); } }
<bean id = "myBean3Factory" class = "com.itheima.instance.factory.MyBean3Factory"/> <bean id = "bean3" factory-bean = "myBean3Factory" factory-method="createBean"/>
測試代碼,這裏只驗收一下實例化是否成功,以及實例化是在什麼步驟中作的:blog
import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InstanceTest3 { @Test public void testFactory(){ String xmlPath= "applicationContext.xml"; ClassPathXmlApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlPath); } }
測試代碼運行結果:it
17:11:20.371 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@737996a0 17:11:20.535 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 6 bean definitions from class path resource [applicationContext.xml] 17:11:20.581 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userDao' 17:11:20.597 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'userService' 17:11:20.628 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'bean1' bean1 實例化 17:11:20.628 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'bean2' bean2 實例化 17:11:20.631 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBean3Factory' bean3工廠實例化中 17:11:20.631 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'bean3' bean3 實例化