After Spring is started, it obtains all Bean instance codes with specific annotations, springbean
This article mainly studies how to obtain all beans with specific annotations after Spring is started, as follows.
Recently, a business scenario encountered in the project is to obtain all beans after the Spring container is started to implement a specific interface object. The first thing that comes to mind is ApplicationContextAware, in setApplicationContext, get all beans through ctx, and then find that the logic is incorrect. This method is not implemented after all beans are initialized. Then, I tried to see if there is any Listener or something, I found ApplicationListener, and Baidu used ApplicationListener. There were a lot of examples, and I recorded my examples.
Very simple, as long as the implementationApplicationListener<ContextRefreshedEvent>
Interface, and then implement the implementation class @ Component. The Code is as follows:
@ Component public class ContextRefreshedListener implements ApplicationListener <ContextRefreshedEvent >{@ Override public void onApplicationEvent (ContextRefreshedEvent event) {// The root container is the Spring container if (event. getApplicationContext (). getParent () = null) {Map <String, Object> beans = event. getApplicationContext (). getBeansWithAnnotation (IMobile. class); for (Object bean: beans. values () {System. err. println (bean = null? "Null": bean. getClass (). getName ();} System. err. println ("===== ContextRefreshedEvent ===" + event. getSource (). getClass (). getName ());}}}
Theevent.getApplicationContext().getBeansWithAnnotation
Obtain all Beans with specific annotations, and traverse all Beans to implement business scenarios.
Summary: this function can initialize system parameters, obtain the list of all interface services in the system, and other functions that need to be initialized after Spring starts.
Extended: In addition to the above events, there are three other events
Closed is called when the container is Closed, Started is theoretically called when the container is Started, and Stopped is called when the container is Closed theoretically.
I stopped the instance through the TomcatServer and only saw Refreshed and Closed. I don't know why, so I can continue to study it when I have time.
Summary
The above is all about getting Bean instance code with specific annotations after Spring is started. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!