Create Bean by calling instance factory method
Instance factory method: The object creation process is encapsulated into another object instance method . When the client needs to request an object, it only needs to call the instance method without concern about the object creation details.
To declare Bean created by instance factory method
Specify the bean that owns the factory method in the bean's factory-bean attribute
Specify the name of the factory method in the factory-method attribute
Use construtor-arg elements to pass method parameters for factory methods
<?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
factroy-bean: 指定工厂bean
factroy-method:指定实例工厂方法.
-->
<bean id="iof" class="com.learn.spring.factory.InstanceObjectFactory"></bean>
<bean id="car1" factory-bean="iof" factory-method="getCar">
<constructor-arg value="bmw"></constructor-arg>
</bean>
</beans>
package com.learn.spring.factory;
import java.util.HashMap;
import java.util.Map;
import com.learn.spring.autowire.Car;
/**
* 获取Car对象的工厂.
* InstanceObjectFactory iof = new InstanceObjectFactory();
*
* Car car = iof.getCar("bmw");
*/
public class InstanceObjectFactory {
private Map<String,Car> cars = new HashMap<String,Car>();
public InstanceObjectFactory(){
cars.put("audi", new Car("Audi", 450000));
cars.put("bmw", new Car("bmw",550000));
}
/**
* 实例工厂方法
*/
public Car getCar(String carName){
return cars.get(carName);
}
}
package com.learn.spring.factory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.spring.autowire.Car;
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("spring-factory.xml");
Car car1 =(Car) ctx.getBean("car1");
System.out.println(car1);
}
}