java - @PostConstruct 和 @PreDestroy 注解的实时应用程序使用

标签 java spring spring-boot spring-mvc servlets

而且在 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/

相关文章:

java - 由于缺少 EmbeddedServletContainerFactory bean,Spring Boot 无法启动 EmbeddedWebApplicationContext

java - 解决 NoClassDefFoundError

spring - 模型无法转换 - Spring Boot 和 Criteria API Join 中的内部错误

java - 使用 JOptionPane API 的自定义对话框不会被释放

java - Apache Tomcat 执行具有相同启动时加载的 Servlet

angularjs - Spring + Hibernate + Angular + Maven + Tomcat 项目文件夹结构问题

java - 为嵌入式 Tomcat 设置 'relaxedQueryChars'

java - Spring引导表单发布大数据需要很长时间才能进入过滤器

java - 为 LDAP 用户设置已经散列的密码(使用 Java)

Java:如何在arraylist中写入计算数据?