The main research in this article is to obtain all beans with specific annotations after Spring is started, as follows.
Recently, I encountered a business scenario in the project, which is to obtain all beans that implement a specific interface object in all beans after the Spring container is started. The first thing I thought of is ApplicationContextAware. In the setApplicationContext, I got all beans through ctx. Later, I found that the logic seemed wrong. This method was not implemented after all beans were initialized. Later, I tried it to see if there were any Listeners and the like, and found a good thing ApplicationListener, and then Baidu used ApplicationListener. It turned out that there were a lot of examples, so I'll record my examples.
It's very simple. Just implement ApplicationListener<ContextRefreshedEvent> interface and then @Component the implementation class. The code is as follows:
@Component public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {@Override public void onApplicationEvent(ContextRefreshedEvent event) {// The root container is a 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());}}} Among them, all Beans collections with specific annotations are obtained through event.getApplicationContext().getBeansWithAnnotation , and then iterate through all beans to implement business scenarios.
Summary and Thoughts: Such a function can initialize system parameters, obtain a list of all interface service in the system, and other functions that need to be initialized after Spring is started.
Let's prolong: In addition to the above events after startup, there are three other events
Closed is called when closing the container, Started is called when the container is started, and Stopped is called when the container is closed.
I started and stopped through TomcatServer, and only saw Refreshed and Closed. I don’t know why, so I will continue to study if I have time.
The above is the entire content of this article about obtaining all bean instance codes with specific annotations after Spring is started. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!