所谓万物皆对象,对于一个 bean 而言,从出生到死亡,他要经历哪些阶段呢?
生命周期
理解对象的生命周期,可以帮助我们更好的做一些扩展。
一个对象从被创建到被垃圾回收,可以大致分为这 5 个阶段:
- 创建/实例化阶段:调用类的构造方法,产生一个新对象;
- 初始化阶段:此时对象已经被创建了,但还未被正常使用,可以在这里做一些初始化的操作;
- 运行使用期:此时对象已经完全初始化好,程序正常运行,对象被使用;
- 销毁阶段:此时对象准备被销毁,需要预先的把自身占用的资源等处理好(如关闭、释放数据库连接);
- 回收阶段:此时对象已经完全没有被引用了,被垃圾回收器回收。
理解了一个 Bean 的生命周期后,下面我们看下SpringFramework怎么对Bean 的生命周期做干预的。
单实例 Bean 的生命周期
init-method & destroy-method
1)创建 Bean
package com.study.spring.a_initmethod;
public class Cat {
private String name;
public Cat() {
System.out.println("Cat 构造方法执行了。。。");
}
public void setName(String name) {
System.out.println("setName方法执行了。。。");
this.name = name;
}
public void init() {
System.out.println(name + " 被初始化了。。。");
}
public void destroy() {
System.out.println(name + " 被销毁了。。。");
}
}
public class Dog {
private String name;
public Dog() {
System.out.println("Dog 构造方法执行了。。。");
}
public void setName(String name) {
System.out.println("setName方法执行了。。。");
this.name = name;
}
public void init() {
System.out.println(name + "被初始化了。。。");
}
public void destroy() {
System.out.println(name + "被销毁了。。。");
}
}
2)分别创建 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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.study.spring.a_initmethod.Cat" init-method="init" destroy-method="destroy">
<property name="name" value="小米米"/>
</bean>
</beans>
@Configuration
public class Config {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Dog dog(){
Dog dog = new Dog();
dog.setName("小勾勾");
return dog;
}
}
3)分别测试xml 和注解驱动
private static void testXml() {
System.out.println("准备初始化IOC容器。。。");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean-initmethod.xml");
System.out.println("IOC容器初始化完成。。。");
System.out.println();
System.out.println("准备销毁IOC容器。。。");
context.close();
System.out.println("IOC容器销毁完成。。。");
}
private static void testAnnotationConfig() {
System.out.println("准备初始化IOC容器。。。");
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
System.out.println("IOC容器初始化完成。。。");
System.out.println();
System.out.println("准备销毁IOC容器。。。");
applicationContext.close();
System.out.println("IOC容器销毁完成。。。")