FactoryBean
①简介
FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
当把FactoryBean的实现类配置为bean时,会将当前类中 getObject() 所返回的对象交给IOC容器管理
将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package org.springframework.beans.factory;import org.springframework.lang.Nullable;public interface FactoryBean<T> {String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";@NullableT getObject() throws Exception;@NullableClass<?> getObjectType();//所提供的对象是否为单例default boolean isSingleton() {return true;}
}
②创建类UserFactoryBean
public class UserFactoryBean implements FactoryBean<User> {public User getObject() throws Exception {return new User();}public Class<?> getObjectType() {return User.class;}
}
③配置bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean class="com.atguigu.spring.factory.UserFactoryBean"></bean></beans>
④测试
public class FactoryBeanTest {@Testpublic void testFactoryBean(){ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");User user = ioc.getBean(User.class);System.out.println(user);}
}