让我们考虑下面的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());
}
}
由于种种原因,我需要调用一个Foo
的方法(即myFoo.shutdown();
)当MyConf1
被销毁。 有没有什么办法可以在没有直接从应用程序上下文中检索bean实例的情况下执行这个操作(通过ApplicationContext.getBean()
)?
案例2
再次,让我们考虑第二Spring配置类:
@Configuration
public class MyConf2 {
@Bean
public ScheduledJob scheduledJob() {
Timer jobTimer = new Timer(true);
return new ScheduledJob(jobTimer);
}
}
这个时候,我需要销毁MyConf2
之前调用jobTimer.cancel()
。事实上,我可以在scheduledJob()
之外实例化jobTimer
,或者使其成为方法的参数,如scheduledJob(Timer jobTimer)
。 然后可以为MyConf2
定义适当的驱逐舰方法。但是,我想知道是否还有其他方法可以继续。
有什么好的建议吗?
注:Foo
,Bar
,Timer
,ScheduledJob
类外部定义。因此,不可能明确定义内部销毁方法。作为假设,我只能修改MyConf1
和MyConf2
。
请仔细阅读我的问题:
当bean是destroy.The输出是
postProcessBeforeDestruction
真的叫。你提到的线程只是第二种情况,我已经解释过如何使用'destroy'方法。然而,正如所说的,我正在寻找其他方法,如果的确有可能(与相关的解释)。 – vdenotaris