我正在尝试在spring单例bean中启动和停止石英调度程序,但是postconstruct被调用了两次,而predestroy根本没有被调用。这个链接说,因为代理,它自然被调用两次,但这是导致异常的后构造方法。我只希望在加载单例bean后调用postConstruct一次。
为什么不尝试使用init-method或尝试实现初始化bean呢?它们提供了postConstruct的替代方法。
当spring bean被卸载时,即当容器被关闭或ConfigurableApplicationContext方法中的close()方法通过其他方式被调用时,preDestroy被调用。
我编写了一个上下文加载器侦听器并更改了web.xml侦听器,因此我只能初始化bean一次。
<listener>
<listener-class>
CustomContextLoaderListener
</listener-class>
</listener>
public class CustomContextLoaderListener extends
org.springframework.web.context.ContextLoaderListener{
Scheduler scheduler;
@Override
public void contextInitialized(javax.servlet.ServletContextEvent event) {
try{
super.contextInitialized(event);
this.scheduler= WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean(Scheduler.class);
}
@Override
public void contextDestroyed(ServletContextEvent event){
super.contextDestroyed(event);
scheduler.stopSchedulers();
}