讓我們考慮下面的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