上文中描述spring加载bean的过程中,有一段关于FactoryBean的处理。所以今天讲一下FactoryBean。从名字上直译就是bean工厂,用来创建bean的。从Spring 3.0 开始, FactoryBean开始支持泛型,即接口声明改为FactoryBean 的形式:
package org.Springframework.beans.factory;
public interface FactoryBean<T> {
/** * 返回由FactoryBean创建的bean实例,如果isSingleton()返回true,则该实 例会放到Spring容器中单实例缓存池中。 */
T getObject() throws Exception;
/** *返回FactoryBean创建的bean类型。 */
Class<?> getObjectType();
/** *返回由FactoryBean创建的bean实例的作用域是singleton还是prototype。 */
boolean isSingleton();
}
下面就开始写今天要演示的2个例子
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class Student {
private String name;
private String classname;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
}
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.FactoryBean;
public class StudentFactoryBean implements FactoryBean<Student> {
private String studentInfo;
@Override
public Student getObject() throws Exception {
Student s=new Student();
String[] studentInfos=studentInfo.split(",");
s.setName(studentInfos[0]);
s.setClassname(studentInfos[1]);
s.setAge(studentInfos[2]);
return s;
}
@Override
public Class<Student> getObjectType() {
return Student.class;
}
@Override
public boolean isSingleton() {
return false;
}
public String getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(String studentInfo) {
this.studentInfo = studentInfo;
}
@Override
public String toString(){
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
}
bean id="studentFactoryBean" class="com.eroadsf.springdemo.factorybean.StudentFactoryBean">
<property name="studentInfo" value="测试1,JAVA班,18"></property>
</bean>
public class Test {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
XmlBeanFactory f=new XmlBeanFactory(new ClassPathResource("spring-context.xml"));
Student s=(Student) f.getBean("studentFactoryBean");
System.out.println("获取student:\n"+s);
StudentFactoryBean sf=(StudentFactoryBean) f.getBean("&studentFactoryBean");//spring就是用&这个来判断获取的是bean还是FactoryBean
System.out.println("获取StudentFactoryBean:\n"+sf);
}
}
结果
获取student:
com.eroadsf.springdemo.factorybean.Student@9d63e96[
name=测试1
classname=JAVA班
age=18
]
获取StudentFactoryBean:
com.eroadsf.springdemo.factorybean.StudentFactoryBean@4d50a1ac[
studentInfo=测试1,JAVA班,18
]