通过工厂配置bean

通过工厂配置bean

1.静态工厂方法

class属性指向静态工厂类

factory-method:指向创建名称

constructor-arg:用于静态方法传参

Java代码:

package com.spring.factory;
import java.util.HashMap;
import java.util.Map;
public class StaticObjFactory {
    private static Map carMap = new HashMap<>();
    static {
        carMap.put("BMW", new FactoryCar("BMW", 300000));
        carMap.put("BenCi", new FactoryCar("BenCi", 600000));
    }
    public static FactoryCar carFatory(String name) {
        return carMap.get(name);
    }
    public static FactoryCar carFatory1(String name) {
        return carMap.get(name);
    }
}

xml代码:


    



    

2.实例工厂方法

需要先创建工厂对象,再低啊用工厂方法创建实例

factory-bean:指向工厂实例

不需要指定class属性

Java代码:

package com.spring.factory;

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

public class InstanceObjFactory {
    private Map carMap = new HashMap<>();

    public InstanceObjFactory() {
        carMap.put("Audi", new FactoryCar("Audi", 300000));
        carMap.put("LuHu", new FactoryCar("LuHu", 600000));
    }

    public FactoryCar carFatory(String brandName) {
        return carMap.get(brandName);
    }
}

xml代码:




    

你可能感兴趣的:(通过工厂配置bean)