欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring中Bean初始化和销毁方法执行的优先级

程序员文章站 2022-05-21 23:05:58
...

Spring有三对初始化和销毁方法

  1. 通过@Bean注解指定initMethod和destroyMethod
  2. 实现InitializingBean和DisposableBean接口
  3. 使用@PostContruct和@PreDestroy

那么问题来了,这三个执行的优先级是什么呢?

定义一个Car类

public class Car implements InitializingBean, DisposableBean {

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

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

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

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

    @PreDestroy
    public void preDestroy(){
        System.out.println("preDestroy");
    }

    @Override
    public void destroy(){
        System.out.println("DisposableBean destroy");
    }

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

定义配置类,并注入

@Configuration
public class MyConfigOfLifeCycle {

    @Bean(initMethod = "initMethod",destroyMethod = "destroyMethod")
    public Car car(){
        return new Car();
    }
}

测试

@Test
public void test04(){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfigOfLifeCycle.class);
    System.out.println("容器创建完成");
    Object car = context.getBean("car");
    context.close();
}

执行结果

car constructor
postConstruct
InitializingBean afterPropertiesSet
initMethod
容器创建完成
preDestroy
DisposableBean destroy
destroyMethod

结论

优先级:@PostConstruct>InitializingBean>通过@Bean指定

相关标签: java