什么是FactoryBean?
- FactoryBean本身已是一个Bean也可以在spring文件中配置,但是他是一个特殊的bean,他的的作用是用于创建某个Bean的实例化对象.

为什么使用FactoryBean?
- 当有些Bean的实例化过程过于的繁琐,导致配置spring文件过于复杂,还不如直接写java代码实例化简单,那么此时就可以利用FactoryBean.
- 将复杂Bean的实例化过程操作写在FactoryBean的getObject()方法之中,而后只需在配置文件中配置这个FactoryBean的实例即可.
示例:使用FactoryBean
public class Person {
private StringicNumber;
private String name;
private String home;
private String mobileNumber;
}
- 创建PersonFactoryBean类,需要实现FactoryBean这个接口
package mao.shu.testFactoryBean;
import org.springframework.beans.factory.FactoryBean;
public class PersonFactoryBean implements FactoryBean<Person> {
@Override
public Person getObject() throws Exception {
Person person = new Person();
person.setIcNumber("789788455972646578");
person.setName("xiemaoshu");
person.setHome("火星");
person.setMobileNumber("78954687934");
return person;
}
@Override
public Class<?> getObjectType() {
return Person.class;
}
@Override
public boolean isSingleton() {
return false;
}
}
- 编写factorybean.xml文件配置工厂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 id="personFactoryBean" class="mao.shu.testFactoryBean.PersonFactoryBean"/>
</beans>
package mao.shu.spring.testFactoryBean;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PersonFactoryBeanTest {
private ApplicationContext app;
@Before
public void before() {
this.app =
new ClassPathXmlApplicationContext("mao/shu/spring/testFactoryBean/factorybean.xml");
}
@Test
public void test(){
Person person = this.app.getBean("personFactoryBean",Person.class);
System.out.println(person);
}
}
