揭秘Spring(五)之init-method与destroy-method

前言

上一节中我们说了bean的初始化调整以及销毁逻辑的两个接口,可以看到非常方便,但是不得不承认具有一定的侵略性,迫使我们改变了原有的很单纯的bean而不得不实现接口,本节中就提供另外的替代方法。

init-method || destroy-method

@Configuration
public class config {

    @Bean(initMethod = "init",destroyMethod = "close")
    public Account account(){
        return new Account("fff");
    }

}
public class Account {
    private String name;
    
    // setter getter constructor

    public void init() throws Exception {
        this.setName("bbfff");
    }


    public void close() throws Exception {
        System.out.println("exit...##############################################");
    }
}
@Test
public void tt(){
    System.out.println(account.getName());
}
bbfff
2019-11-10 15:15:40.536  INFO 22056 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService applicationTaskExecutor
exit...##############################################

输出和上一节一摸一样,可以看到主要是在config中的bean定义处设置了init-method 和 destroy-method ,同时,用这种方法,我们的方法名也是完全自己定义,比如我就定义为了 init 和 close ,在Account中也不需要再实现复杂的接口。

总结

其实看了上一节,本节基本没啥可看的了。我们平时这两种方式条一种就可以了,如果真相都用的话,前一节的两个方法执行时机均比本节两个方法早一步,其实大概很少会两个都用啦,所以我就不再实验,感兴趣的小伙伴儿可以自己去试下~

经验分享 程序员 微信小程序 职场和发展