手动从spring BeanFactory 获取bean (二)

自己的类 实现org.springframework.beans.factory.BeanFactoryAware 接口  

BeanFactoryAware 接口中只有一个方法  setBeanFactory(BeanFactory beanFactory)

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class SpringBeanFactory implements BeanFactoryAware {

	private static BeanFactory beanFactory;
	
	public static Object getBean(String beanName) {
		 return beanFactory.getBean(beanName);
	}
	
	public static <T> T getBean(String beanName, Class<T> clazs) {
		 return clazs.cast(getBean(beanName));
	}
	
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		SpringBeanFactory.beanFactory = beanFactory;
	}
}


applicationContext.xml

<bean id="springBeanFactory" class="com.xx.service.util.SpringBeanFactory" />

遗留一个问题

spring 容器什么时候 会调用BeanFactoryAware 实现类  也就是说调用SpringBeanFactory   setBeanFactory方法 ?

posted on 2012-03-21 14:38  YangJin  阅读(821)  评论(0编辑  收藏  举报