美文网首页SpringFramework
通过工厂配置bean

通过工厂配置bean

作者: 逗比寨主 | 来源:发表于2019-07-15 18:42 被阅读0次

    通过工厂配置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<String, FactoryCar> 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代码:

    <bean id="factoryCar1" class="com.spring.factory.StaticObjFactory" factory-method="carFatory">
        <constructor-arg name="name" value="BenCi"></constructor-arg>
    </bean>
    
    <bean id="factoryCar2" class="com.spring.factory.StaticObjFactory" factory-method="carFatory1">
        <constructor-arg name="name" value="BMW"></constructor-arg>
    </bean>
    

    2.实例工厂方法

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

    factory-bean:指向工厂实例

    不需要指定class属性

    Java代码:

    package com.spring.factory;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class InstanceObjFactory {
        private Map<String, FactoryCar> 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 id="instanceObjFactory" class="com.spring.factory.InstanceObjFactory"></bean>
    
    <bean id="factoryCar3" factory-bean="instanceObjFactory" factory-method="carFatory">
        <constructor-arg name="brandName" value="Audi"></constructor-arg>
    </bean>
    

    相关文章

      网友评论

        本文标题:通过工厂配置bean

        本文链接:https://www.haomeiwen.com/subject/vesokctx.html