Spring中为bean指定InitMethod和DestroyMethod的执行方法是什么

Spring中为bean指定InitMethod和DestroyMethod的执行方法是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1.创建一个类

/**
 * @author: zhaobin
 * @date: 2021/11/25 10:16
 * @description:
 */
public class Cat {

    public Cat(){
        System.out.println("先初始化构造器");
    }

    public void start(){
        System.out.println("start方法");
    }

    public void destroy(){
        System.out.println("销毁方法");
    }
}

2.创建一个bean

/**
 * @author: zhaobin
 * @date: 2021/11/25 10:14
 * @description:
 */
@Configuration
public class EventConfig {

    @Bean(initMethod = "start",destroyMethod = "destroy")
    public Cat create(){
        Cat cat = new Cat();
        System.out.println("接下来初始化Cat中的start方法");
        //return一个宠物类,这样spring容器中就有了这个Cat类,才能执行initMethod中的start方法.以及容器关闭的时候执行销毁的方法
        return cat;
    }
}

3.加载的顺序为: create方法->Cat类的构造器->create方法中的输出打印->Cat类中的start方法->Cat类中的destroy方法

关于Spring中为bean指定InitMethod和DestroyMethod的执行方法是什么问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。