Spring中初始化和销毁方法的执行顺序

在Spring中我们可以通过InitializingBean、@PostConstruct、以及制定init-method等方式在bean初始化时做一些初始化相关的操作,以及通过DisposableBean、@PreDestroy和destroy-method等方式在bean销毁时执行一些销毁操作。那么这些不同方式的执行顺序是什么呢?接下来我们通过实战来看下具体的执行顺序。

定义bean

package com.example.demo.service;

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

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

public class HelloService implements InitializingBean, DisposableBean {

    private String name;

    public HelloService(String name) {
        this.name = name;
    }

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

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

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean name=" + name);
    }

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

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

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

xml中配置bean声明

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="com.example.demo.service.HelloService" init-method="initMethod" destroy-method="destroyMethod">
        <constructor-arg index="0" value="chyang" />
    </bean>
</beans>

run项目

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(locations = {"classpath:applicationContext.xml"})
public class ArthasDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ArthasDemoApplication.class, args);
    }

}

执行结果

PostConstruct name=chyang
InitializingBean name=chyang
initMethod name=chyang

PreDestroy name=chyang
DisposableBean name=chyang
destroyMethod name=chyang

结论

  • 初始化执行顺序:constructor(构造器) -> PostConstruct -> InitializingBean -> init-method
  • 销毁执行顺序:PreDestroy -> DisposableBean -> destroy-method
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值