FactoryBean是spring框架定义的一个接口. 用于自定义bean的整个实例化过程;
说到实例化,默认spring bean只有给beanFactory注册beanDefinition就可以自动完成实例化, 这种方式能满足绝大多数的实例化需求. FactoryBean是为了满足复杂实例化的需求,比如aop生成代理对象, 自定义接口给接口生成代理对象等。
image.png
用法.
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
// 定义beanDefinition
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(UserComponentFactoryBean.class);
// 自动注入
builder.setAutowireMode(2);
annotationConfigApplicationContext.registerBeanDefinition("userComponentFactoryBean", builder.getBeanDefinition());
annotationConfigApplicationContext.refresh();
public class UserComponentFactoryBean implements FactoryBean {
private UserComponent userComponent;
@Override
public UserComponent getObject() throws Exception {
if (userComponent == null) {
userComponent = new UserComponent();
System.out.println("------------ factoryBean----" + userComponent.hashCode());
}
return userComponent;
}
@Override
public Class> getObjectType() {
return UserComponent.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
这里使用注册beanDefinition的方式让beanFactory感知到有FactoryBean,当然也可以用包扫描的方式加@Component。
这里UserComponentFactoryBean的getObject()方法获取对象实例只是示范,并不规范。
注意:如果UserCompontFactoryBean有依赖其他bean,FactoryBean不会自动完成注入。
如果需要获取bean关联的FactoryBean需要在beanName前加上 &
MyBatise在FactoryBean上的应用
MapperFactoryBean
程序急需要定义Mapper接口,MapperFactoryBean就会为其生成代理对象.
Dubbo在FactoryBean上的应用
ReferenceBean
dubbo会为标识为@Reference的注入使用javassist生成具体的bean.
Spring Context在FactoryBean上的应用
ScopedProxyFactoryBean
给声明了@RefreshScope的类生成代理, 处理配置实时刷新同步的问题