spring的众多扩展方式之一, 可以实现这个接口自定义一个bean对象的生成工厂。在一些bean对象想创建比较复杂或者需要在创建前后需要做一些动作时候比较实用的。
demo示例
最终要生成的bean对象的类
1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.zw.dubbo.factorybean;
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void sayName() {
System.out.println("my name is " + name + ".");
}
}FactoryBean的实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.zw.dubbo.factorybean;
import org.springframework.beans.factory.FactoryBean;
public class StudentBean implements FactoryBean<Student> {
private String studentName;
public Student getObject() throws Exception {
studentName = "小明";
return new Student(studentName);
}
public Class<?> getObjectType() {
return Student.class;
}
}spring配置文件,test_factory_bean.xml
1
2
3
4
5
6
7
<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-4.3.xsd">
<bean id="xiaoming" class="com.zw.dubbo.factorybean.StudentBean"/>
</beans>启动类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package com.zw.dubbo.factorybean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestFactoryBean {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:test_factory_bean.xml"});
context.start();
Student xiaoming = (Student) context.getBean("xiaoming");
xiaoming.sayName();
StudentBean studentBean = (StudentBean) context.getBean("&xiaoming");
System.out.println(studentBean.toString());
}
}程序执行结果
1
2
3
4
521:21:35.424 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ea30797
21:21:35.854 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [test_factory_bean.xml]
21:21:35.962 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'xiaoming'
my name is 小明.
com.zw.dubbo.factorybean.StudentBean@7d70d1b1