Spring之FactoryBean(工厂Bean)
org.springframework.beans.factory.FactoryBean是一个接口,是Spring中用于定义自定义服务的核心接口,他本身是在bean工厂中定义的一个bean,同时又是用于创建另一个Spring服务对象的工厂。
FactoryBean.java
package org.springframework.beans.factory;
public interface FactoryBean {
<fontsize=3> /**
* Return an instance (possibly shared or independent) of the object
* managed by this factory. As with a BeanFactory, this allows
* support for both the Singleton and Prototype design pattern.
*
If this method returns null, the factory will consider the
* FactoryBean as not fully initialized and throw a corresponding
* FactoryBeanNotInitializedException.
* @return an instance of the bean (should not be null; a null value
* will be considered as an indication of incomplete initialization)
* @throws Exception in case of creation errors
* @see FactoryBeanNotInitializedException
<fontsize=3> */
Object getObject() throws Exception;
Class getObjectType();
boolean isSingleton();
}
下面是FactoryBean的getObject方法的调用层次。
我们可以看出,当我们用BeanFactory或ApplicationContext去那getBean()时,如果这个Bean是被一个BeanFactory,那么BeanFactory得到的会是FactoryBean.getObject()的对象。
<spanlang=zh-cn>下面是AbstractBeanFactory的getObjectForSharedInstance(String,Object)方法。
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it&aposs a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (beanInstance instanceof FactoryBean) {
if (!isFactoryDereference(name)) {
// Return bean instance from factory.
FactoryBean factory = (FactoryBean) beanInstance; //Cast toFactoryBean.
if (logger.isDebugEnabled()) {
logger.debug("Bean with name &apos" + beanName + "&apos is a factory bean");
}
try {
beanInstance = factory.getObject(); // Get the realObject
}
catch (Exception ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
if (beanInstance == null) {
throw new FactoryBeanNotInitializedException(
beanName, "FactoryBean returned null object: " +
"probably not fully initialized (maybe due to circular bean reference)");
}
}
else {
// The user wants the factory itself.
if (logger.isDebugEnabled()) {
logger.debug("Calling code asked for FactoryBean instance for name &apos" + beanName + "&apos");
}
}
}
Spring通过FactoryBean来提供内置的许多有用的核心服务。当然你也可以实现自己的FactoryBean,但是你大不可以不必这样做,Spring已经提供了大量的。
org.springframework.jndi JndiObjectFactoryBean:JNDI LookUp。
org.springframework.orm.hibernate3. LocalSessionFactoryBean:配置本地的Hibernate SessionFactory的工厂bean。
org.springframework.aop.framework ProxyFactoryBean:通用的用于获得AOP代理的工厂bean。
org.springframework.transaction.interceptor.TransactionProxyFactoryBean:用于为对象创建事务代理,用于实现简介易用申明性事务管理。
…………etc
http://www.writely.com/View.aspx?docid=bdd75r9hmc98j