而且在 spring-boot 应用程序中,我们不会在任何地方关闭上下文,那么 Web 应用程序如何管理此关闭上下文并销毁工作的 bean。
实际上这个Web应用程序何时会触发上下文关闭并触发@PreDestroy注释。
最佳答案
@PostConstruct is very helpful if you wanted to do anything after all your beans are initialized. I had the following use case where I had used @PostConstruct
我有 11 个 customerProcess 类的实现,在每次操作之后,我必须调用一个不同的进程,因此我们需要 Autowiring 其所有实现,而不是使用 postconstruct 来获取一个枚举映射,我们向该映射提供了类名,然后我们得到了相应的bean,所以Post Construct在这里为我工作
@PostConstruct
private void init() {
CustomerProcessTask.getClassList().forEach( aClass -> {
final CustomerTask customerTypeBean = applicationContext.getBean(aClass);
factory.put(aClass,customerTypeBean);
});
}
@PreDestroy 有多种用例,当您需要关闭打开的数据库连接或在调用 applicationContext.close 之前回滚某些内容时,可以使用它。但对于 Web 应用程序,dispatcherServlet 创建 applicationContext 并在服务器停止时关闭上下文。我们不需要显式调用 applicationContext.close()。
@PreDestroy()
public void dataSourceDestroy() throws SQLException {
rollbackUnCommittedTransaction();
}
}
关于java - @PostConstruct 和 @PreDestroy 注解的实时应用程序使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225611/