• Spring之使用工厂方法配置Bean


    public class Car {
        
        private String brand;
        private double price;
        
        
        public Car(String brand, double price) {
            this.brand = brand;
            this.price = price;
        }
        public String getBrand() {
            return brand;
        }
        public void setBrand(String brand) {
            this.brand = brand;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        @Override
        public String toString() {
            return "Car [brand=" + brand + ", price=" + price + "]";
        }
    }
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 静态工厂方法:直接调用某一个类的静态方法就可以返回bean的实例
     * @author zhang
     *
     */
    
    public class StaticCarFactory {
    
        private static Map<String,Car> map = new HashMap<String, Car>();
        static{
            map.put("Audi",new Car("Audi",30000));
            map.put("Ford",new Car("Ford",20000));
        }
        
        public static Car getCar(String name){
            return map.get(name);
        }
    }
    import java.util.HashMap;
    import java.util.Map;
    
    public class InstanceCarFactory {
        
        private Map<String,Car> cars = null;
        
        public InstanceCarFactory() {
            cars = new HashMap<String, Car>();
            cars.put("ford",new Car("ford",20000));
            cars.put("audi",new Car("audi",30000));
        }
        
        public Car getCar(String name){
            return cars.get(name);
        }
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns: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">
        
        <!-- 通过静态工厂方法来配置bean实例 -->
        <bean id="car" class="com.auguigu.spring.beans.factory.StaticCarFactory"
            factory-method="getCar">
            <constructor-arg value="Audi"></constructor-arg>
        </bean>
        
        <!-- 配置工厂的实例 -->
        <bean id="carFactory" class="com.auguigu.spring.beans.factory.InstanceCarFactory"></bean>
        <!-- 通过实例工厂方法来配置bean -->
        <bean id="cars" factory-bean="carFactory" factory-method="getCar">
            <constructor-arg value="ford"></constructor-arg>
        </bean>
        
    </beans>

    之所以描述很少,因为我觉得他们不是很重要,在业务生产中用不到

  • 相关阅读:
    Linux的iptables和netfilter
    adb安装电视apk
    令牌桶实现服务器限流
    观察者模式代码实现
    Windows系统安装Oracle 11g 数据库
    Gitlab安装后 启动之后报错502
    Git两库合并历史记录
    Maven打包时指定对应环境的配置文件
    HierarchicalDataTemplateGridControl
    自定义CommandHandler
  • 原文地址:https://www.cnblogs.com/sdnu-zhang/p/8528024.html
Copyright © 2020-2023  润新知