factory-bean: 指定使用哪个工程实例,实例工厂,非静态方法创建bean
factory-method:指定使用哪个工厂实例的方法。静态工厂,静态方法创建bean
判断的依据是 创建bean的方法是否存在 static 修饰符。
具体code 如下:
package com.gientech.factoryMethod;
public class Person {
private int id;
private String name;
private int age;
private String gender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
创建静态方法
package com.gientech.factoryMethod;
public class PersonStaticFactory {
public static Person getPerson(String name){
Person person = new Person();
person.setId(1);
person.setName(name);
return person;
}
}
package com.gientech.factoryMethod;
public class PersonInstanceFactory {
public Person getPerson(String name){
Person person = new Person();
person.setId(2);
person.setName(name);
return person;
}
}
创建配置文件
<?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">
<!-- factory-method : 静态工厂, 指定使用哪个工厂实例的方法 -->
<bean id="person" class="com.gientech.factoryMethod.PersonStaticFactory" factory-method="getPerson">
<constructor-arg value="zhangsan"></constructor-arg>
</bean>
<!-- factory-bean : 实例工厂,指定使用哪个工程实例, -->
<bean id="personInstanceFactory" class="com.gientech.factoryMethod.PersonInstanceFactory"></bean>
<bean id="person2" class="com.gientech.factoryMethod.Person" factory-bean="personInstanceFactory" factory-method="getPerson">
<constructor-arg value="lisi"></constructor-arg>
</bean>
</beans>
创建测试类
package com.gientech.factoryMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryMethodTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("factoryMethod.xml");
Person person = ac.getBean("person", Person.class);
System.out.println(person);
Person person2 = ac.getBean("person2", Person.class);
System.out.println(person2);
}
}
运行结果如下:
factoryMethod 执行流程
nstantiateUsingFactoryMethod方法执行流程图如下: