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初始化之后调用

输出结果

Spring四种初始化与销毁方法执行顺序对比_第1张图片

被注入对象

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);
    }
}

你可能感兴趣的:(Java,Spring)