spring-bean-init(bean初始化方法及销毁方法顺序示例)

spring的生命周期方法给用户提供了多种扩展方式

构建Bean时:

  1.     使用@PostConstruct
  2.     实现InitializingBean接口的afterPropertiesSet方法
  3.     自定义init-method(并在@Bean中或者xml中配置init-method)

销毁Bean时:

  1.     @PreDestroy
  2.     destroy-method
  3.     DisposableBean -- destroy

构建Bean三者的执行顺序示例:

public class Pig implements InitializingBean {

    @PostConstruct
    public void postConst() {
        System.out.println("@PostConstruct...");
    }

    public void initMethod() {
        System.out.println("initMethod...");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean--afterPropertiesSet...");
    }
}

测试:

public class BeanInitMethodDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory();
        ctx.register(BeanInitMethodDemo.class);
        ctx.refresh();
        ctx.close();
    }

    @Bean(initMethod = "initMethod")
    public Pig pig() {
        return new Pig();
    }
}

输出:

@PostConstruct...
InitializingBean--afterPropertiesSet...
initMethod...

可见执行顺序为:@PostConstruct --> InitializingBean --> 自定义init-method

销毁Bean执行顺序

示例代码:

public class Pig implements DisposableBean {
    @PreDestroy
    public void preDestroy() {
        System.out.println("@PreDestroy...");
    }
    @PreDestroy
    public void destroyMethod() {
        System.out.println("自定义destroyMethod...");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean--destroy()");
    }
}

测试:

public class BeanDestroyMethodDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(BeanDestroyMethodDemo.class);
        ctx.refresh();
        Object pig = ctx.getBean("pig");
        System.out.println(pig);
        ctx.close();
    }

    @Bean(destroyMethod = "destroyMethod")
    public Pig pig() {
        return new Pig();
    }
}

输出:

com.demo.beans.definition.pojo.Pig@7a187f14
@PreDestroy...
自定义destroyMethod...
DisposableBean--destroy()

可见:执行顺序为

@PreDestroy --> 自定义destroyMethod --> DisposableBean--destroy()方法
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值