• spring之通过实例工厂方法配置Bean


    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 com.gong.spring.beans.factory;
    
    import java.util.HashMap;
    import java.util.Map;
    
    //实例工厂方法,先要创建工厂方法本身,再调用工厂的实例方法返回Bean的实例
    public class InstanceFactory {
        private Map<String, Car> cars = null;
        public InstanceFactory() {
            cars = new HashMap<String,Car>();
            cars.put("baoma",new Car("baoma",200000));
            cars.put("benchi",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: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 id="carFactory" class="com.gong.spring.beans.factory.InstanceFactory"></bean>
        <!-- 通过实例工厂方法配置Bean -->
        <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();
        }
    }

    输出:

  • 相关阅读:
    在服务端合并css和js以减少http请求数
    IE6 IE7(Q) IE8(Q) 不完全支持 !important 规则
    js 获取高度,宽度,绑定事件
    一段很有用的获取页面高度的js
    filter用AJAX取回动态数据进行筛选的时候,必须同时指定标签类型和 ID,才能正常进行筛选,要不然在Firefox下会出错
    匿名函数的链式调用
    js从数组中删除指定值(不是指定位置)的元素
    纯CSS的方法解决文字溢出与截断的问题
    javascript sort 排序
    WIN10系统找不到MSVCP120.dll
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12155949.html
Copyright © 2020-2023  润新知