The factory methods to create a Spring Bean

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43687990/article/details/102533540

Creating Bean via static factory method
calls the static factory method to create Bean is the process of creating objects encapsulate a static method, when a client needs an object, simply call the static method, without concern for the details to create an object, to declare by Bean created a static method, you need to specify the class has a method to change the factory in the configuration file Bean class attribute, the same time specify the name of the factory method in the factory-method attribute. Finally, transmission parameters for the method using the element

The following sample code

//准备一个Car类
public Car{
	private String brand;
	public Car(String brand){
		thsi.brand = brand;
	}
	
	public void setBrand(String brand){
			this.brand = brand
	}
}

//静态工厂类

public CarStaticFactory{
	private static Map<String,Car> cars = new HashMap<String,Car>();
	staitc{
	cars.put("audi",new Car("audi"));
	cars.put("ford",new Car("ford"));
}
public static Car getCar(String brand){
	return cars.get(brand);
}
}

//xml文件中的配置
<bean id="car1" class="CarStaticFactory的全类名" factory-method="getCar">
		<constructor-arg value="audi"></constructor-arg>
	</bean>

Bean instance is created by calling the factory method
instance factory method: the creation of an encapsulated object in a method in another object instance. When a client needs to request object, simply call an instance method without the need to change the process of creating an object of interest
to declare created by Bean instance factory method
in the bean factory-bean attribute that owns the factory method specified in the Bean
at factory -method attribute specified in the name of the process plant
using construtor-arg element method delivery method is factory

Code Example (using the above Car class):

public InstanceCarFactory{
public Map<String,Car> cars =null;
	
	public InstanceCarFactory() {
		cars = new HashMap<String, Car>();
		cars.put("audi", new Car("audi",400000));
		cars.put("ford", new Car("ford",500000));
	}
	
	public Car getCar(String brand) {
		return cars.get(brand);
	}
}

//xml文件中的配置
<bean id="InstanceCarFactory" class="InstanceCarFactory的全类名"></bean>
	
	<bean id="car2" factory-bean="InstanceCarFactory" factory-method="getCar">
		<constructor-arg value="ford"></constructor-arg>
	</bean>

Guess you like

Origin blog.csdn.net/qq_43687990/article/details/102533540