比较init-method,afterPropertiesSet和BeanPostProcessor其三init-method

175 阅读1分钟

init-method,afterPropertiesSet和BeanPostProcessor的作用都是能使用户在spring bean初始化时完成自定义的方法,但实现的方式各有不同,顺序从先到后依次是:BeanPostProcessor的postProcessBeforeInitialization > afterPropertiesSet > init-method > BeanPostProcessor的postProcessAfterInitialization。其先后顺序与spring的调用有关,在spring加在bean的源码类AbstractAutowireCapableBeanFactory类中的invokeInitMethods有清晰的展现。

  1. 概念:1、init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。

  2. 注册:init-method需要在applicationContext.xml配置文档中bean的定义里头写明。例如:<bean id=

    "TestBean"

    class=

    "nju.software.xkxt.util.TestBean"

    init-method=

    "init"