Reference: http://www.shareniu.com/article/73.htm
The need is to write a method of my writing to run after the project started, before using the Redis message listener, feeling can follow the listener this idea, and then thought of Sringboot listener
Two. The following types of events are currently supported in spring boot:
-
Applicationfailedevent: This event is an action when spring boot fails
-
Applicationpreparedevent: Triggered when context is ready
-
Applicationreadyevent: Trigger When context is ready to complete
-
applicationstartedevent:spring Boot Boot Listener class
-
Springapplicationevent: Get Springapplication
-
Applicationenvironmentpreparedevent: Environment prepared beforehand
Three. Use of listeners
First: First define a listener class that you use and implement the Applicationlistener interface.
@Componen
PublicclassMessagereceiverImplementsApplicationlistener<applicationreadyevent> { PrivateLogger Logger = Loggerfactory.getlogger (messagereceiver.class); PrivateUserService UserService =NULL; @Override Public voidonapplicationevent (Applicationreadyevent event) {Configurableapplicationcontext ApplicationContext=Event.getapplicationcontext (); //resolve UserService always emptyUserService = Applicationcontext.getbean (userservice.class);
System.out.println ("name" +userservice.getname ()); }}
Second: Register the custom Listener with the Addlisteners method in the Springapplication class
Public class Application { publicstaticvoid main (string[] args) { new springapplication (application. Class); Application.addlisteners (new messagereceiver ()); Application.Run (args);} }
Start Project
Use of Springboot listener Applicationlistener-Monitor applicationreadyevent events