FactoryBean
当配置文件中<bean>的class属性配置的实现类是FactoryBean时,通过 BeanFactory#getBean()方法返回的不是FactoryBean本身,而是FactoryBean#getObject()方法所返回的对象,相当于FactoryBean#getObject()代理了getBean()方法
public interface FactoryBean<T> { /** * Return an instance (possibly shared or independent) of the object * managed by this factory. */ T getObject() throws Exception; Class<?> getObjectType(); boolean isSingleton(); }
ApplicationContextAware
实现ApplicationContextAware的bean,会在Bean初始化的时候自动调用setApplicationContext,然后就可以获取spring的上下文,通过spring的上下文就可以获取到spring的一些信息,还可以获取其他的bean
public interface ApplicationContextAware extends Aware { /** * Set the ApplicationContext that this object runs in. * Normally this call will be used to initialize the object. */ void setApplicationContext(ApplicationContext applicationContext) throws BeansException; }
InitializingBean
实现InitializingBean,在bean初始化之前会调用afterPropertiesSet()
public interface InitializingBean { /** * Invoked by a BeanFactory after it has set all bean properties supplied * (and satisfied BeanFactoryAware and ApplicationContextAware). */ void afterPropertiesSet() throws Exception; }
关于初始化的问题,还有其他几种方法实现
init-method、@PostConstruct、InitializingBean#afterPropertiesSet哪个先执行,这又是个问题
Constructor > @PostConstruct > InitializingBean > init-method,构造函数最优先
详见下面blog