bean_生命周期与管理


bean生命周期
  • bean生命周期:bean从创建到销毁的整体过程
  • bean生命周期控制:在bean创建后到销毁前做一些事情
  • 初始化容器
    1. 创建对象(内存分配)
    2. 执行构造方法
    3. 执行属性注入(set操作)
    4. 执行bean初始化方法
  • 使用bean
    1. 执行业务操作
  • 关闭 / 销毁容器
    1. 执行 bean 销毁方法
bean销毁时机
  • 容器关闭前触发 bean 的销毁
  • 关闭容器方式
    • 手工关闭容器
      configurableApplicationContext 接口 close() 操作
    • 注册关闭钩子,在虚拟机推出前先关闭容器再退出虚拟机
      configurableApplicationContext 接口 registerShutdownHook() 操作
public class AppForLifeCycle {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
       // ctx.close();
       // ctx.registerShutdownHook();
    }
}
bean管理

bean作用范围

package com.itheima.dao.impl;

import com.itheima.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

@Repository()
@Scope("prototype")
public class BookDaoImpl implements BookDao {

    public void save() {
        System.out.println("book dao save...");
    }
	
    @PostConstruct
    public void init() {
        System.out.println("init...");
    }
    
    @PreDestroy
    public void destroy() {
        System.out.println("destroy");
    }
}

文章作者: han yue
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 han yue !
评论
  目录