Spring启动后再执行

因某些需求需要在开机是启动监听,然后调用数据库查询数据。遇到的问题是执行方法太快,导致Service还没有成功注入,抛出空指针异常。
解决办法:

public class FaceRecordListen implements ApplicationListener<ContextRefreshedEvent> {
@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null){//排除projectName-servlet context  
            //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。  
            //other code....
            //XXXXXService.XXXXXX
       }  

    }
}

猜你喜欢

转载自blog.csdn.net/vadonmo/article/details/78829647