在 Spring 启动时执行方法 [英] Execute method on startup in Spring

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

问题描述

应用程序第一次启动时,有没有Spring 3的特性来执行一些方法?我知道我可以使用 @Scheduled 注释来设置方法,它会在启动后立即执行,但随后会定期执行.

Is there any Spring 3 feature to execute some methods when the application starts for the first time? I know that I can do the trick of setting a method with @Scheduled annotation and it executes just after the startup, but then it will execute periodically.

推荐答案

如果应用程序启动"是指应用程序上下文启动",那么是的,有 很多方法可以做到这一点,最简单的(对于单例 bean,无论如何)使用 @PostConstruct 注释您的方法.查看链接以查看其他选项,但总的来说它们是:

If by "application startup" you mean "application context startup", then yes, there are many ways to do this, the easiest (for singletons beans, anyway) being to annotate your method with @PostConstruct. Take a look at the link to see the other options, but in summary they are:

  • @PostConstruct 注释的方法
  • afterPropertiesSet()InitializingBean 回调接口定义
  • 自定义配置的 init() 方法
  • Methods annotated with @PostConstruct
  • afterPropertiesSet() as defined by the InitializingBean callback interface
  • A custom configured init() method

从技术上讲,这些是 bean 生命周期的钩子,而不是上下文生命周期,但在 99% 的情况下,两者是等效的.

Technically, these are hooks into the bean lifecycle, rather than the context lifecycle, but in 99% of cases, the two are equivalent.

如果您需要专门挂钩上下文启动/关闭,那么您可以实现 Lifecycle 接口,但这可能是不必要的.

If you need to hook specifically into the context startup/shutdown, then you can implement the Lifecycle interface instead, but that's probably unnecessary.

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

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