Springboot bean初始化方法InitializingBean

spring boot InitializingBean接口使用总结

  • 被spring管理
  • 实现InitializingBean接口 
  • 重写afterPropertiesSet方法

InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

代码入下

@Component
@PropertySource("classpath:common/testFile.properties")
//注意这个实现InitializingBean接口,重写afterPropertiesSet方法 public class Test implements InitializingBean { private static final Logger logger = LoggerFactory.getLogger(Test.class); @Value("${hdfs.user.root}") private String hdfs; @Override public void afterPropertiesSet() throws Exception { System.out.println("init"); } }

测试代码,测试每次调用这个方法都会重新初始化,还是只初始化一次

@Component
@RestController
public class Hello {

    private static final Logger logger = LoggerFactory.getLogger(Hello.class);
    
    @Autowired
    private Test test;

    @RequestMapping("/get")
    public void get() {
        System.out.println("从别的配置文件中读取"+test.getHdfs());
    }
}

测试结果,只对bean进行了一次初始化,以后并不会在调用它了

这说明在spring初始化bean的时候,如果bean实现了InitializingBean接口,会自动调用afterPropertiesSet方法。

总结:

1、Spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中通过init-method指定,两种方式可以同时使用。

2、实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率要高一点,但是init-method方式消除了对spring的依赖。

3、如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。


__EOF__

本文作者彬在俊
本文链接https://www.cnblogs.com/erlou96/p/16878451.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   彬在俊  阅读(702)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示