Spring大纲汇总-Bean的生命周期

对Person类、Student类重写生命周期方法

//Student部分代码
public class Student {
	private String name;
	private String gender;
	private Integer age;

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public void myInit(){

		System.out.println("这是Student的初始化方法...");

	}
	public void myDestroy(){

		System.out.println("这是Student的销毁方法...");

	}

}
//Person类部分代码
public class Person {
	
	public void myInit(){

		System.out.println("这是Person的初始化方法...");

	}
	public void myDestroy(){

		System.out.println("这是Person的销毁方法...");

	}
}

在IOC容器中,配置Bean时,将Person设置成单例并重写生命周期方法。将Student设置成多例并重写生命周期方法。

<bean id="person01"  class="com.cuco.bean.Person" scope="singleton" init-method="myInit" destroy-method="myDestroy">
<!-- 使用property标签为Persion对象的属性进行赋值 -->
<property name="lastName" value="张三"></property>
<property name="age" value="18"></property>
<property name="gender" value="男"></property>
<property name="email" value="94401550@qq.com"></property>
</bean>

<bean id="student01" class="com.cuco.bean.Student" scope="prototype" init-method="myInit" destroy-method="myDestroy">
<property name="name" value="Cuco"></property>
<property name="gender" value="girl"></property>
<property name="age" value="21"></property>
</bean>

测试单例Person是在什么时候创建:在IOC容器实例化时创建。当关闭容器时,单例Bean也跟着销毁。

多例Student在被调用时创建Bean,并且每次创建的Bean所引用的地址不同。当容器关闭时,多例Bean并不会跟着销毁。

public class IOCTestNew {
	
	//获取IOC容器
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");
	@Test
	public void test() {
		Student student = (Student)ioc.getBean("student01");
		Student student1 = (Student)ioc.getBean("student01");
		System.out.println(student == student1);
		
		ioc.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值