FactoryBean对象设计是为了生成简化对象, 在BeanDefinition加载的时候FactoryBean的beanName会带有特殊前缀&.
public interface FactoryBean<T> { @Nullable T getObject() throws Exception; @Nullable Class<?> getObjectType(); default boolean isSingleton() { return true; } }
在BeanFactory中的定义:
public interface BeanFactory { // FactoryBean前缀, 用于区分FactoryBean产生的bean. 如果myJndiObject为FactoryBean, 可以用&myJndiObject获取工厂类 /** * Used to dereference a {@link FactoryBean} instance and distinguish it from * beans <i>created</i> by the FactoryBean. For example, if the bean named * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject} * will return the factory, not the instance returned by the factory. */ String FACTORY_BEAN_PREFIX = "&";
// ......... }
实际应用中如ProxyFactoryBean可以将代理的具体细节隐藏起来, 只需要通过getObject获取代理. 还有CronTriggerFactoryBean配置使用quartz时候简化配置等. 以下为一个示例demo:
DecorationFactoryBean.java
/** * bean 装饰工厂 * @author */ public class DecorationFactoryBean implements FactoryBean<Bean> { @Override public Bean getObject() throws Exception { Bean bean = new Bean() ; bean.setName("在FactoryBean统一处理属性") ; return bean; } @Override public Class<?> getObjectType() { return Bean.class; } }
ioc-FactoryBean.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean > </beans>