使用 Spring MVC 在应用程序启动时执行 Java 类 [英] Executing a Java class at application startup using Spring MVC

查看:62
本文介绍了使用 Spring MVC 在应用程序启动时执行 Java 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Spring MVC 在应用程序启动时执行 Java 类的最佳方法是什么?

What is the best way to execute a Java class at application startup using Spring MVC ?

推荐答案

不一定有最佳"方式.像往常一样,有很多方法可以做到,最佳"是最适合您的项目的:

There's not necessarily a "best" way. As usual, there are many ways to do it, and the "best" is whichever fits into your project the best:

  1. 在 XML 中的 bean 元素上使用 init-method="...",如 cjstehno 所述
  2. 实现 Spring 的 InitializingBean 接口.当部署在 ApplicationContext,创建 bean 时将调用 afterPropertiesSet() 方法.
  3. 使用 @PostConstruct.同样,如果部署到 ApplicationContext,则在创建 bean 时将调用带注释的方法.
  4. 如果您的 bean 更像是要绑定到 Spring 生命周期的基础设施 bean,请实施 ApplicationListener<ContextRefreshedEvent>.onApplicationEvent(..) 方法将在 Spring 启动期间被调用,您可以在那里做任何您需要的工作.
  1. Use init-method="..." on a bean element in XML, as cjstehno mentioned
  2. Implement Spring's InitializingBean interface. When deployed in an ApplicationContext, the afterPropertiesSet() method will be called when the bean is created.
  3. Annotate a method on a bean with @PostConstruct. Again, if deployed to an ApplicationContext, the annotated method will be called when the bean is created.
  4. If your bean is more of an infrastructure bean to be tied into the Spring lifecycle, implement ApplicationListener<ContextRefreshedEvent>. The onApplicationEvent(..) method will be called during Spring's startup, and you can do whatever work you need there.

这篇关于使用 Spring MVC 在应用程序启动时执行 Java 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆