InitializingBean 与 CommandLineRunner(或者ApplicationRunner) 两个接口里面都提供了启动后调用的抽象方法用于我们进行拓展。日常使用时,两者皆可。
代码语言:java复制@FunctionalInterface
public interface CommandLineRunner extends Runner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
void run(String... args) throws Exception;
}
代码语言:java复制public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
}
两者的区别如下:
1、调用时机 CommandLineRunner 要晚于 InitializingBean 调用
2、InitializingBean 在bean初始化后调用,而CommandLineRunner是在整个环境初始化完成后调用