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);
    }
}
posted @ 2023-10-12 10:32  扎Zn了老Fe  阅读(124)  评论(0编辑  收藏  举报  来源