13、生命周期-InitializingBean和DisposableBean

13、生命周期-InitializingBean和DisposableBean

  • InitializingBean接口
package org.springframework.beans.factory;

public interface InitializingBean {
    // 当BeanFactory创建完对象,并且设置完属性之后调用 = init
    void afterPropertiesSet() throws Exception;
}
  • DisposableBean接口
package org.springframework.beans.factory;

public interface DisposableBean {
    // 当对象销毁时调用
    void destroy() throws Exception;
}
13.1 新建Cat 实现接口
package com.hw.springannotation.beans;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * @Description TODO
 * @Author hw
 * @Date 2018/11/28 19:32
 * @Version 1.0
 */
public class Cat implements InitializingBean, DisposableBean {

    public Cat() {
        System.out.println("Cat constructor...");
    }

    public void destroy() throws Exception {
        System.out.println("Cat destroy...");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("Cat afterPropertiesSet...");
    }
}
13.2 注入Cat
    @Bean
    public Cat cat() {
        return new Cat();
    }
13.3 测试

1221855-20181128194626251-2054938284.png

转载于:https://www.cnblogs.com/Grand-Jon/p/10030819.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Bean 的作用域和生命周期是 Spring 框架中非常重要的概念。 作用域:Spring Bean 的作用域指的是 Bean 实例的创建和销毁方式。Spring 支持多种 Bean 的作用域,包括 Singleton、Prototype、Request、Session、Global Session 等。 - Singleton:单例模式,一个 Bean 实例在整个应用中只被创建一次。 - Prototype:原型模式,每次从容器中获取 Bean 时都会创建一个新的实例。 - Request:每个 HTTP 请求都会创建一个 Bean 实例,该 Bean 实例仅在当前 HTTP 请求内有效。 - Session:每个 HTTP Session 都会创建一个 Bean 实例,该 Bean 实例仅在当前 HTTP Session 内有效。 - Global Session:该作用域仅适用于基于 Portlet 的 Web 应用,每个全局 HTTP Session 都会创建一个 Bean 实例,该 Bean 实例仅在当前全局 HTTP Session 内有效。 生命周期:Spring Bean 的生命周期指的是 Bean 实例的创建、初始化和销毁过程。Spring 容器负责管理 Bean 的生命周期,Bean 生命周期包括以下几个阶段: - 实例化:创建 Bean 实例。 - 属性赋值:将 Bean 实例的属性值注入到 Bean 实例中。 - 初始化:调用 Bean 的初始化方法。 - 使用:Bean 实例可以被容器和其他 Bean 使用。 - 销毁:容器关闭或者手动销毁 Bean 实例时,调用 Bean 的销毁方法。 Spring Bean 的生命周期可以通过 BeanPostProcessor、InitializingBean 和 DisposableBean 接口、@PostConstruct 和 @PreDestroy 注解等方式进行定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值