Spring projects start automatically performs a specified method

Spring projects start automatically performs a specified method

   点关注不迷路,欢迎再访!		

ApplicationListener implement interfaces, and implements onApplicationEvent (ContextRefreshedEvent contextRefreshedEvent) Method

springmvc:

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
            //需要执行的方法
        }
    }
}

Why do first judgment?

Spring there are two containers: one is the root application context, the other is our own projectName-servlet context (container as a child of the root application context). In this case, it will cause onApplicationEvent method is executed twice. To avoid the problems mentioned above, we can only root application context initialization after the completion of call logic code to initialize other vessel is completed, does nothing.

Published 101 original articles · won praise 33 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_39443053/article/details/103448264