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

查看:280
本文介绍了使用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. 使用init-在XML中的bean元素上的method =...,如cjstehno提到的那样

  2. 实现Spring的 InitializingBean 接口。部署在 ApplicationContext ,在创建bean时将调用afterPropertiesSet()方法。

  3. 使用 @ PostConstruct 。同样,如果部署到ApplicationContext,则在创建bean时将调用带注释的方法。

  4. 如果您的bean更多是要绑定到Spring生命周期的基础结构bean,请实现< a href =http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationListener.html =noreferrer> ApplicationListener < < a href =http://static.springsource.org/spring/docs/3.0.0.M3/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html =noreferrer> 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天全站免登陆