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