Spring bean实例化的方式

实例化过程如图,方式如图。

甩代码。

方式一:构造方法

搞一个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"/>

  

方式二:静态工厂方法调用

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>

  

方式三:实例化工厂,调用工厂实例的方法

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"/>

  

测试代码,这里只验收一下实例化是否成功,以及实例化是在什么步骤中做的:

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);
	}
}

  

测试代码运行结果:

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 实例化

  

猜你喜欢

转载自www.cnblogs.com/zhizhiyin/p/10684776.html