Spring中FactoryBean
FactoryBean是Spring提供的一种整合第三方框架常用的机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件的创建的详细过程和繁琐细节都屏蔽起来,只把最简介的使用界面展示出来
将来我们整合mybatis时,Spring就是通过FactoryBean机制来帮助我们创建SqlSession Factory对象的
以下是整个使用FactoryBean的代码流程:
1.创建类UserFactoryBean
package com.qcw.spring.factory;
import com.qcw.spring.pojo.User;
import org.springframework.beans.factory.FactoryBean;
/**
* FactoryBean是一个接口,需要创建一个类实现该接口
* 其中由三个方法:
* getObject():通过一个对象交给IOC容器管理
* getObjectType():设置所提供对象的类型
* isSingleton():所提供的对象是否单例
*/
public class UserFactoryBean implements FactoryBean<User> {
public User getObject() throws Exception {
return new User();
}
public Class<?> getObjectType() {
return User.class;
}
}
2.配置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.qcw.spring.factory.UserFactoryBean"></bean>
</beans>
3.测试
package com.qcw.spring.test;
import com.qcw.spring.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryBeanTest {
@Test
public void testFactoryBean(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-factory.xml");
User user = ioc.getBean(User.class);
System.out.println("user = " + user);
}
}