Created by bean instance factory method

1. static factory method

/ **
* static factory methods: directly call a static method of a class can return the bean instance

*
* /

1) to establish a static factory
public class StaticCarFactory {
Private static the Map <String, Car> = new new cars the HashMap <String, Car> ();
static {
cars.put ( "Audi", new new Car ( "Audi", 300000)) ;
cars.put ( "baoma", new new Car ( "baoma", 500000));
}
// static factory method
public static Car getCar (String name) {
return cars.get (name);
}
} 2) profile

<! - configured by a static factory method bean, attention is not a configuration example of a static factory method, but examples of the configuration bean ->
<! -
class attributes: point full class name of a static factory method
factory-method: Method pointing Factory name
constructor-arg: If the plant parameters need to pass method, is used to configure the parameters constructor-arg
->
<the bean ID = "CAR1" class = "com.mww.spring.factory.StaticCarFactory" = factory-method " getCar ">
<constructor-Arg value =" Audi "> </ Arg-constructor>
</ the bean>

2. instance factory method

1) the establishment of factories

/ **
* instance factory method: the method of Example plant, i.e. the plant itself now need to create, and then calls the instance factory method to return an instance of the bean
*
*
* /
public class InstanceCarFactory {
Private the Map <String, Car> cars = null;
InstanceCarFactory public () {
cars new new = the HashMap <> ();
cars.put ( "Audi", new new Car ( "Audi", 300000));
cars.put ( "Bama", new new Car ( "Baoma", 500000) );
}
public Car getCar (String Brand) {
return cars.get (Brand);
}
}

2) Profile

<! - example of configuration of the plant ->
<the bean ID = "carFactory" class = "com.mww.spring.factory.InstanceCarFactory"> </ the bean>
<! - by way of example a method to configure the bean ->
< ! -
factory-the bean properties: points to an instance factory method of the bean
factory-method: the method names point to the factory
constructor-arg: If the plant parameters need to pass method, is used to configure the parameters constructor-arg
->
<= the bean ID "CAR2" the bean-Factory = "carFactory" Factory-Method = "getCar">
<constructor-Arg value = "Bama"> </ Arg-constructor>
</ the bean>

3.main

public class Main {

public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
Car car = (Car) ctx.getBean("car1");
System.out.println(car);
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}

}

Guess you like

Origin www.cnblogs.com/mwwex/p/12070721.html