BeanFactoryAware

在使用spring编程时,常常会遇到想根据bean的名称来获取相应的bean对象,这时候,就可以通过实现BeanFactoryAware来满足需求,代码很简单:

@Service
public class BeanFactoryHelper implements BeanFactoryAware {
    
    private static BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
    
    public static Object getBean(String beanName){

     if(beanFactory == null){
            throw new NullPointerException("BeanFactory is null!");
        }

     return beanFactory.getBean(beanName); 
  } 
}

还有一种方式是实现ApplicationContextAware接口

@Service
public class ApplicationContextHelper implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    public static Object getBean(String beanName){
        if(applicationContext == null){
            throw new NullPointerException("ApplicationContext is null!");
        }
        return applicationContext.getBean(beanName);
    }

}

阅读更多

没有更多推荐了,返回首页