简介
spring容器在创建当前bean时,会去调用接口BeanFactoryAware扩展点。BeanFactoryAware有个方法setBeanFactory,入参是beanFactory。
重写setBeanFactory方法,能够获取到spring容器,进而从spring容器获取指定bean。如果该bean尚未创建,会触发bean的创建流程。
示例
@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);
}
}