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

Posted 西西嘛呦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
}

输出:

以上是关于spring之通过实例工厂方法配置Bean的主要内容,如果未能解决你的问题,请参考以下文章

Spring之Bean

Spring中Bean的配置方式之通过工厂方法

spring之通过静态工厂方法配置Bean

Spring中Bean的配置方式之FactoryBean

Spring(十三):使用工厂方法来配置Bean的两种方式(静态工厂方法&实例工厂方法)

Spring之Bean的注入