如何在弹簧加载应用程序上下文后立即执行作业?
我想在加载Spring上下文后运行一些作业,但我不知道如何执行此操作。
你知道怎么做吗?
另一种可能性是将侦听器注册到应用程序上下文事件 ()。基本上它与skaffman的解决方案相同,只需实现:
org.springframework.context.ApplicationListener<org.springframework.context.event.ContextRefreshedEvent>
而不是生命周期。它只有一种方法,而不是三种方法。:-)
如果要在 Spring 的上下文启动后运行作业,则可以使用 和 事件 。ApplicationListener
ContextRefreshedEvent
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
// do what you want - you can use all spring beans (this is the difference between init-method and @PostConstructor where you can't)
// this class can be annotated as spring service, and you can use @Autowired in it
}
}