Spring通过工厂方法配置Bean

前言:

Spring配置Bean的方法有很多,这里只介绍通过工厂方法配置Bean。
所谓工厂即含有批量的Bean,可根据传入的参数条件返回对应的Bean实例。

工厂又分两种:

静态工厂通过静态方法返回Bean实例。
实例工厂通过实例方法返回Bean实例。

区别两者:
前者配置Bean的时候是配置实例Bean,而不是静态工厂。
后者配置Bean的时候需要先配置实例工厂,然后根据传参来配置实例Bean


先来介绍第一种方法:静态工厂

直接调用某一个类的静态方法就可以返回Bean实例

先创建静态工厂类

public class MyStaticFctory {

    private static Map<String,Car> cars = new HashMap<String,Car>();

    static{
        cars.put("大众",new Car("大众",10000));
        cars.put("奥迪",new Car("奥迪",40000));
    }

    public static Car getCar(String name){
       return cars.get(name);
    }
}

再配置xml配置文件
通过静态工厂配置Bean,注意不是配置静态工厂实例,而是配置bean实例

 <bean id="car" class="hello.MyStaticFctory" factory-method="getCar">
        <constructor-arg value="奥迪"></constructor-arg>
 </bean>

注意:

class:静态工厂全类名
factory-method:获得bean实例的静态方法。
constructor-arg:如果返回实例的静态方法有属性,就是它来赋值

测试:

 public static void main(String[] args) throws SQLException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Car car = (Car) applicationContext.getBean("car");
        System.out.println(car);
    }

输出:

Car{name='奥迪', price=40000}

第二种方法:实例工厂方法创建Bean

将对象的创建过程封装到另一个对象实例的方法离,
当客户端需要请求对象的时候,
只需要简单的调用该实例方法而不需要关心对象的创建过程。

实例工厂类:

public class MyFactory {
    private  Map<String,Car> cars = new HashMap<String,Car>();

    public MyFactory(){
        cars.put("大众",new Car("大众",10000));
        cars.put("奥迪",new Car("奥迪",40000));
    }

    public Car getCar(String name){
        return cars.get(name);
    }
}

配置xml文件:
实例工厂的方法,需要创建工厂本身,再调用工厂的实例方法来返回bean的实例。

 <bean id="myfactory" class="hello.MyFactory"></bean>
    <bean id="car2" factory-bean="myfactory" factory-method="getCar">
        <constructor-arg value="大众"></constructor-arg>
    </bean>

测试:

 public static void main(String[] args) throws SQLException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Car car = (Car) applicationContext.getBean("car2");
        System.out.println(car);
    }

输出:

Car{name='大众', price=10000}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值