Create a bean by calling a static factory method
Calling a static factory method to create a bean is to encapsulate the process of object creation into a static method . When the client needs the object, it only needs to simply call the static method without caring about the details of creating the object.
To declare a bean created by a static method, you need to specify the class of the factory method in the bean's class attribute, and specify the name of the factory method in the factory-method attribute. Finally, use the <constrctor-arg> element for the method Pass method parameters.
<?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
class: 静态工厂类
factroy-method: 静态工厂方法.
-->
<bean id="car" class="com.learn.spring.factory.StaticObjectFactory"
factory-method="getCar" >
<constructor-arg value="audi"></constructor-arg>
</bean>
</beans>
package com.learn.spring.factory;
import java.util.HashMap;
import java.util.Map;
import com.learn.spring.autowire.Car;
/**
* 获取Car对象的工厂.
* Car car = StaticObjectFactory.getCar("audi");
*/
public class StaticObjectFactory {
private static Map<String,Car> cars = new HashMap<String,Car>();
static{
cars.put("audi", new Car("Audi", 450000));
cars.put("bmw", new Car("bmw",500000));
}
/**
* 静态工厂方法
*/
public static 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 car =(Car) ctx.getBean("car");
System.out.println(car);
}
}