Spring实例工厂方法


Spring 实例工厂方法

通过调用实例工厂方法创建 bean:

  • 实例工厂方法:将对象的创建过程封装到另外一个对象实例的方法里。当客户端需要请求对象时 , 只需要简单的调用该实例方法而不需要关心对象的创建细节。
  • 要声明通过实例工厂方法创建的 bean
  1. 在 bean 的factory-bean 属性里指定拥有该工厂方法的bean。
  2. 在 factory-method 属性里指定该工厂方法的名称。
  3. 使用 元素为工厂方法传递方法参数。

Spring的配置文件

<!--配置工厂的实例-->
<bean id="instanceFactory" class="com.an.factory.InstanceFactory"/>
<!--通过工厂的工厂方法获取bean-->
<bean id ="car2" factory-bean="instanceFactory" factory-method="getCar">
    <constructor-arg value="auto"/>
</bean>

要实例的工厂类

package com.an.factory;

import com.an.things.Car;

import java.util.HashMap;
import java.util.Map;

public class InstanceFactory {
    private Map<String, Car> cars =null;
    
    public InstanceFactory(){
        cars = new HashMap<>();
        cars.put("audi",new Car("audi","shanghai",333.0));
        cars.put("auto",new Car("auto","shanghai",233.0));
    }
    public Car getCar(String name){
        return cars.get(name);
    }
}

主函数

package com.an.factory;

import com.an.things.Car;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

待创建的bean的类

public class Car {
    private String brand;
    private String corp;
    private double price;
    private int maxSpeed;
    public Car(){
        System.out.println("创建了一个汽车!");
    }
    public Car(String brand, String corp, double price) {
        this.brand = brand;
        this.corp = corp;
        this.price = price;
    }
    
    public Car(String brand, String corp, int maxSpeed) {
        this.brand = brand;
        this.corp = corp;
        this.maxSpeed = maxSpeed;
    }
    
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
    
    public String getCorp() {
        return corp;
    }
    
    public void setCorp(String corp) {
        this.corp = corp;
    }
    
    public double getPrice() {
        return price;
    }
    
    public void setPrice(double price) {
        this.price = price;
    }
    
    public int getMaxSpeed() {
        return maxSpeed;
    }
    
    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
    
    @Override
    public String toString() {
        return "Car{" +
            "brand='" + brand + '\'' +
            ", corp='" + corp + '\'' +
            ", price=" + price +
            ", maxSpeed=" + maxSpeed +
            '}';
    }
}

输出结果:

Car{brand='auto', corp='shanghai', price=233.0, maxSpeed=0}

文章作者: Bxan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Bxan !
  目录