InitializingBean 与 CommandLineRunner

InitializingBean 与 CommandLineRunner(或者ApplicationRunner) 两个接口里面都提供了启动后调用的抽象方法用于我们进行拓展。日常使用时,两者皆可。

@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;

}
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是在整个环境初始化完成后调用

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容