Spring四种初始化与销毁方法执行顺序对比

结论

  1. @PostConstruct与@PreDestroy最先执行
  2. 实现InitializingBean与DisposableBean接口其次
  3. @Bean里的initMethod和destroyMethod最后执行

注意:

  1. Spring的接口BeanPostProcessor
    postProcessBeforeInitialization(Object bean, String beanName)方法, 会在bean初始化之前调用
    postProcessAfterInitialization(Object bean, String beanName)方法, 会在bean初始化之后调用

输出结果

在这里插入图片描述

被注入对象

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Person {

    @Bean(initMethod = "init", destroyMethod = "destroy2")
    public User user() {
        return new User();
    }
}

被初始化对象

package com.example.demo;

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

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class User implements InitializingBean, DisposableBean {

	// javax
    @PostConstruct
    public void initPostConstruct() {
        System.out.println("@PostConstruct");
    }
    
	@PreDestroy
    public void destroy3() {
        System.out.println("@PreDestroy");
    }
    
	// 实现接口
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean");
    }
    
    @Override
    public void destroy() {
        System.out.println("DisposableBean");
    }
    
	// @Bean
    public void init() {
        System.out.println("@Bean");
    }
    
    public void destroy2() {
        System.out.println("@Bean");
    }
}

测试类

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Test
    void test() throws InterruptedException {
        Thread.sleep(5000);
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值