createBean中 factory-method创建bean实例
作用
静态工厂/非静态工厂创建bean实例
factory-method 实例
前期准备bean
public class Student {
private String studentName;
}
提前声明的静态工厂
public class StaticFactoryMethod {
public static Student getStudent(){
Student student = new Student();
student.setStudentName("li si");
return student;
}
}
提前声明的非静态工厂
public class NonStaticFactoryMethod {
public Student getStudent(){
Student student = new Student();
student.setStudentName("zhang san");
return student;
}
}
xml文件中声明 factory-method属性
<?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="studentA" class="com.spring.learn.bean.factorymethod.StaticFactoryMethod" factory-method="getStudent"/>
<bean id="nonStaticFactoryMethod" class="com.spring.learn.bean.factorymethod.NonStaticFactoryMethod"/>
<bean id="studentB" class="com.spring.learn.common.staff.Student" factory-bean="nonStaticFactoryMethod" factory-method="getStudent"/>
</beans>
测试方法
public class SpringFactoryMethodStart {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean/factorymethod/factorymethod.xml");
Student studentA = ac.getBean("studentA", Student.class);
Student studentB = ac.getBean("studentB", Student.class);
System.out.println(studentA.getStudentName());
System.out.println(studentB.getStudentName());
}
}
factory-method 源码流程
instanceWrapper = createBeanInstance(beanName, mbd, args);
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, factoryMethodToUse, argsToUse));
return bw;
|