如何正确销毁 Spring 配置类

vde*_*ris 3 java spring inversion-of-control

情况1

让我们考虑以下 Spring 配置:

@Configuration
public class MyConf1 {

    @Bean
    public Foo getFoo() {
        // Foo class is defined as part of an external lib.
        return new Foo();
    }

    @Bean
    public Bar getBar() {
        return new Bar(getFoo());
    } 

 }
Run Code Online (Sandbox Code Playgroud)

由于某些原因,我需要在销毁时调用 aFoo的方法(即myFoo.shutdown();MyConf1。有没有办法在不直接从应用程序上下文中检索 bean 实例的情况下执行此操作(通过ApplicationContext.getBean())?

案例二

同样,让我们​​考虑第二个 Spring 配置类:

@Configuration
public class MyConf2 {

    @Bean
    public ScheduledJob scheduledJob() {
        Timer jobTimer = new Timer(true);
        return new ScheduledJob(jobTimer);
    }

 }
Run Code Online (Sandbox Code Playgroud)

这一次,我需要jobTimer.cancel()在销毁之前调用MyConf2。确实,我可以将jobTimer外部实例化scheduledJob(),或将其设为方法的参数,如scheduledJob(Timer jobTimer). 然后就可以为 定义一个合适的销毁方法MyConf2。但是,我想知道是否还有其他方法可以继续。

有什么好的建议吗?

注意: Foo , Bar, Timer,ScheduledJob类是在外部定义的。因此,不可能明确定义内部销毁方法。作为假设,我只能修改MyConf1MyConf2

Arc*_*hit 5

我建议在课堂上定义一个destroy()方法(用 注释@PreDestroyFoo

同样,修改ScheduledJob

public class ScheduledJob {

    private Timer timer;

    public ScheduledJob(Timer timer){
        this.timer = timer;
    }

    @PreDestroy
    public void destroy(){
        timer.cancel();
    }
}
Run Code Online (Sandbox Code Playgroud)

并添加destroyMethod参数@Bean

@Configuration
public class MyConf2 {

    @Bean(destroyMethod = "destroy")
    public ScheduledJob scheduledJob() {
        Timer jobTimer = new Timer(true);
        return new ScheduledJob(jobTimer);
    }

}
Run Code Online (Sandbox Code Playgroud)