init-method,afterPropertiesSet和BeanPostProcessor的作用都是能使用户在spring bean初始化时完成自定义的方法,但实现的方式各有不同,顺序从先到后依次是:BeanPostProcessor的postProcessBeforeInitialization > afterPropertiesSet > init-method > BeanPostProcessor的postProcessAfterInitialization。其先后顺序与spring的调用有关,在spring加在bean的源码类AbstractAutowireCapableBeanFactory类中的invokeInitMethods有清晰的展现。
-
afterPropertiesSet
-
概念:InitializingBean接口为bean提供了初始化后的处理方法,它只包括afterPropertiesSet方法,凡是实现该接口的类,在bean的属性初始化之后都会执行该方法。它的调用时间点在当前类bean的属性设置完成之后,这也就是为什么afterPropertiesSet方法没有参数。
-
如何使用
-
实现InitializingBean
-
重写afterPropertiesSet方法
- public class Account implements InitializingBean { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public Account(String name){ this.name=name; } @Override public void afterPropertiesSet() throws Exception { this.setName("bbfff"); } }
-
-
如何注册:@Compoent
-