且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Spring MVC在应用程序启动时执行Java类

更新时间:2021-09-10 03:26:43

不一定是***的办法。像往常一样,有很多方法可以做到这一点,***的是最适合你项目的:

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. 使用init-在XML中的bean元素上的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.