The spring configuration by Bean instance factory method

Car.java

package com.gong.spring.beans.factory;

public class Car {
    private String name;
    private double price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Car(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }
    
}

InstanceFactory.java

Package Penalty for com.gong.spring.beans.factory; 

Import java.util.HashMap;
 Import java.util.Map; 

// instance factory method, first create factory method itself, then call the instance method returns the Bean factory instance 
public  class {InstanceFactory
     Private the Map <String, Car> cars = null ;
     public InstanceFactory () { 
        cars = new new the HashMap <String, Car> (); 
        cars.put ( "baoma", new new Car ( "baoma", 200000 )); 
        cars .put ( "Benchi", new new Car ( "Benchi", 300000 )); 
    } 
    public Car getCar(String name) {
        return cars.get(name);
    }
}

beans-factory.xml

<? XML Version = "1.0" encoding = "UTF-. 8" ?> 
< Beans xmlns = "http://www.springframework.org/schema/beans" 
    xmlns: the 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 " > 
    
    <-! examples of configuration of the plant -> 
    < the bean ID = "carFactory" class = "com.gong.spring.beans.factory.InstanceFactory" > </ the bean > 
    <-! arranged Bean plants by the method of example -> 
    <bean id="car" factory-bean="carFactory" factory-method="getCar">
        <constructor-arg value="baoma"></constructor-arg>
    </bean>
</beans>

Main.java

package com.gong.spring.beans.factory;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //1.创建spring的IOC容器对象
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
        //2.从容器中获取Bean实例
        Car car = (Car) ctx.getBean("car");
        System.out.println(car.toString());
        ctx.close();
    }
}

Output:

Guess you like

Origin www.cnblogs.com/xiximayou/p/12155949.html