packagecom.imooc.ioc.demo2; /*** Bean的实例化的三种方式:采用无参数的构造方法的方式*/publicclassBean1 { publicBean1(){ System.out.println("Bean1被实例化了..."); } }
packagecom.imooc.ioc.demo2; /*** Bean的实例化三种方式:静态工厂实例化方式*/publicclassBean2 { } packagecom.imooc.ioc.demo2; /*** Bean2的静态工厂*/publicclassBean2Factory { publicstaticBean2createBean2(){ System.out.println("Bean2Factory的方法已经执行了..."); returnnewBean2(); } }
packagecom.imooc.ioc.demo2; /*** Bean的实例化三种方式:实例工厂实例化*/publicclassBean3 { } packagecom.imooc.ioc.demo2; /*** Bean3的实例工厂*/publicclassBean3Factory { publicBean3createBean3(){ System.out.println("Bean3Factory执行了..."); returnnewBean3(); } }
<!--第一种:无参构造器的方式--><beanid="bean1"class="com.imooc.ioc.demo2.Bean1"/><!--第二种:静态工厂的方式--><beanid="bean2"class="com.imooc.ioc.demo2.Bean2Factory"factory-method="createBean2"/><!--第三种:实例工厂的方式--><beanid="bean3Factory"class="com.imooc.ioc.demo2.Bean3Factory"/><beanid="bean3"factory-bean="bean3Factory"factory-method="createBean3"/>
packagecom.imooc.ioc.demo2; importorg.junit.Test; importorg.springframework.context.ApplicationContext; importorg.springframework.context.support.ClassPathXmlApplicationContext; /*** Bean的实例化的三种方式*/publicclassSpringDemo2 { @Testpublicvoiddemo1(){ // 创建工厂ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml"); // 通过工厂获得类的实例:Bean1bean1= (Bean1)applicationContext.getBean("bean1"); } @Testpublicvoiddemo2(){ // 创建工厂ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml"); // 通过工厂获得类的实例:Bean2bean2= (Bean2)applicationContext.getBean("bean2"); } @Testpublicvoiddemo3(){ // 创建工厂ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml"); // 通过工厂获得类的实例:Bean3bean3= (Bean3)applicationContext.getBean("bean3"); } }