3和5偷懒没有做。
LifeCycle类:
package com.kiong.spring6;
public class LifeCycle {
private String name;
public LifeCycle(String name) {
this.name = name;
}
public LifeCycle() {
System.out.println("1.创建bean对象,调用无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("2.给bean对象设置属性值");
this.name = name;
}
//初始化的方法
public void initMethod(){
System.out.println("4.初始化bean对象,调用指定的初始化方法");
}
//销毁的方法
public void destroyMethod(){
System.out.println("7.销毁bean对象,调用指定的销毁方法");
}
}
bean-life.xml
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="lifeCycle" class="com.kiong.spring6.LifeCycle"
scope="singleton" init-method="initMethod" destroy-method="destroyMethod">
<property name="name" value="Steve"></property>
</bean>
</beans>
TestLifeCycle类:
package com.kiong.spring6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestLifeCycle {
public static void main(String[] args) {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("bean-life.xml");
LifeCycle lifeCycle = context.getBean("lifeCycle",LifeCycle.class);
System.out.println("6.完成创建bean对象了,可以使用了");
//销毁
context.close();
}
}
执行结果: