Spring 获取 bean
spring最重要的功能是作为bean容器,方便的提供bean的初始化和存取服务。我们使用spring, 也正是为了避免自己去创建或者管理对象。 因此应该尽量从spring容器中去拿bean, 而不是自己去new.
如何在自己的程序中灵活的拿到被spring管理的bean呢,当然是从beanFactory里拿了
下面是一个简单的例子,通过BeanFactory拿到bean
public class ServiceLocator implements BeanFactoryAware {
private static BeanFactory beanFactory = null;
/**
* @param servName bean
*/
public static Object getService(String servName) {
return beanFactory.getBean(servName);
}
/**
*
* @param servName bean
* @param clazz
*/
@SuppressWarnings("unchecked")
// 通过这个方法拿到bean
public static Object <strong>getService</strong>(String servName, Class clazz) {
return beanFactory.getBean(servName, clazz);
}
public void setBeanFactory(BeanFactory factory) throws BeansException {
this.beanFactory = factory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
代码里通过实现BeanFactoryAware接口,获取spring的beanFactory, 再通过getService方法里的beanFactory.getBean拿到想要的对象。
BeanFactoryAware接口非常简单,如下:
public interface BeanFactoryAware {
/**
* Callback that supplies the owning factory to a bean instance.
* <p>Invoked after the population of normal bean properties
* but before an initialization callback such as
* {@link InitializingBean#afterPropertiesSet()} or a custom init-method.
* @param beanFactory owning BeanFactory (never <code>null</code>).
* The bean can immediately call methods on the factory.
* @throws BeansException in case of initialization errors
* @see BeanInitializationException
*/
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
就一个方法 setBeanFactory。 目的就是把factory实例化成一个bean
除了实现BeanFactory接口之外,还可以实现其它的接口,最常用的应该是ApplicationContextAware接口, 这个接口也只有一个方法
setApplicationContext,
目的也是将
applicationContext实例化成一个bean.
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;