具体的生命周期过程
bean
对象创建(调用无参构造器)
给
bean
对象设置属性
bean
对象初始化之前操作(由
bean
的后置处理器负责)
bean
对象初始化(需在配置
bean
时指定初始化方法)
bean
对象初始化之后操作(由
bean
的后置处理器负责)
bean
对象就绪可以使用
bean
对象销毁(需在配置
bean
时指定销毁方法)
IOC
容器关闭
实体类:
package com.xiongdada.spring.pojo;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User() {
System.out.println("生命周期:1、创建对象");
}
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
System.out.println("生命周期:2、依赖注入");
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void initMethod() {
System.out.println("生命周期:3、初始化");
}
public void destroyMethod() {
System.out.println("生命周期:5、销毁");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
}
xml文件:
<bean class="com.xiongdada.spring.pojo.User" scope="singleton" init-method="initMethod" destroy-method="destroyMethod">
<property name="id" value="1001"></property>
<property name="username" value="admin"></property>
<property name="password" value="123456"></property>
<property name="age" value="23"></property>
</bean>
测试类:
@Test
public void testLife() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("spring_lifecycle.xml");
User bean = ac.getBean(User.class);
System.out.println(bean);
System.out.println("生命周期:4、通过IOC容器获取bean并使用");
ac.close();
}
输出结果:
注意:
若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行
若bean额作用域为多例时,生命周期的前三个步骤会在获取bean时执行
例子:
单例:
scope="singleton"
@Test
public void testLife() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("spring_lifecycle.xml");
// User bean = ac.getBean(User.class);
// System.out.println(bean);
System.out.println("生命周期:4、通过IOC容器获取bean并使用");
ac.close();
}
输出:
多例:
scope="prototype"
@Test
public void testLife() {
ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("spring_lifecycle.xml");
// User bean = ac.getBean(User.class);
// System.out.println(bean);
System.out.println("生命周期:4、通过IOC容器获取bean并使用");
ac.close();
}
结果: