解决方法1:
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
try {
if(event.getApplicationContext().getParent()==null){ //root application context 没有parent,他就是老大.
elasticsearchService.init();
}
} catch (Exception e) {
e.printStackTrace();
}
}
解决方法2:用需要执行的方法上用@PostConstruct
@PostConstruct
public void init() {
//xxx
}
根据不同的需要使用,两个解决方法性质不一样。
springboot中执行顺序为:constructor -> @PostConstruct -> afterPropertiesSet -> onApplicationEvent