How to execute jobs just after spring loads application context?

后端 未结 5 1487
萌比男神i
萌比男神i 2021-02-01 03:14

I want to run some jobs just after loading the Spring context but I do not know how to do this.
Do you have any idea how to do that?

5条回答
  •  迷失自我
    2021-02-01 03:57

    If you want run a job after Spring's context start, then you can use the ApplicationListener and the event ContextRefreshedEvent.

    public class YourJobClass implements ApplicationListener{
    
        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
    
        }
    }
    

提交回复
热议问题