簡(jiǎn)介
spring容器在創(chuàng)建當(dāng)前bean時(shí),會(huì)去調(diào)用接口BeanFactoryAware擴(kuò)展點(diǎn)隅津。BeanFactoryAware有個(gè)方法setBeanFactory未斑,入?yún)⑹莃eanFactory虹统。
重寫(xiě)setBeanFactory方法染簇,能夠獲取到spring容器,進(jìn)而從spring容器獲取指定bean模燥。如果該bean尚未創(chuàng)建咖祭,會(huì)觸發(fā)bean的創(chuàng)建流程。
示例
@Service
public class BeanFactoryUtils implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public <T> T getBean(String beanName) {
return (T) beanFactory.getBean(beanName);
}
}