问题描述
当应用程序第一次启动时,是否有任何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 $ c定义$ c>回调接口
- 自定义配置的init()方法
- Methods annotated with
@PostConstruct
afterPropertiesSet()
as defined by theInitializingBean
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.
如果你需要专门挂钩上下文启动/关闭,然后你可以,但这可能是不必要的。
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中启动时执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!