Spring扩展接口-BeanFactoryAware
简介
调用时机:spring容器在创建当前bean时,会去调用接口BeanFactoryAware扩展点。
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
BeanFactoryAware有个方法setBeanFactory,入参是beanFactory。重写时,能够获取到spring容器,进而从spring容器获取指定bean。如果该bean尚未创建,会触发bean的创建流程。
用途示例
内部获取Spring的BeanFactory,封装获取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);
}
}
本文来自博客园,作者:扎Zn了老Fe,转载请注明原文链接:https://www.cnblogs.com/itThinking/p/17771109.html