java如何正确销毁Spring配置类
案例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());
}
}
出于某些原因,当MyConf1
被销毁时,我需要调用Foo
的方法(即myFoo.shutdown();
)。
有没有办法在不直接从应用程序上下文检索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
# 1 楼答案
您可以实现
DestructionAwareBeanPostProcessor
接口,该接口可以在bean被销毁时添加销毁前回调。在该接口中,方法postProcessBeforeDestruction
是这样做的,请参见以下内容:注意方法
requiresDestruction
应该返回true,否则当bean应该销毁时方法postProcessBeforeDestruction
将不会调用我有个测试:
当bean被销毁时,
postProcessBeforeDestruction
真正调用。输出为:# 2 楼答案
请参见下页http://forum.spring.io/forum/spring-projects/container/48426-postconstruct-and-predestroy-in-javaconfig
DisposableBean应该可以帮助你解决案例1
# 3 楼答案
我建议在
Foo
类中定义destroy()
方法(用@PreDestroy
注释)类似地,修改
ScheduledJob
类并在
@Bean
中添加destroyMethod
param