4.2 使用工厂方法创建Bean

这篇博客探讨了如何在Spring中利用静态和实例工厂方法创建Bean。内容包括静态工厂方法的优势,如无需创建工厂对象,以及实例工厂方法的使用,其中Spring会负责创建工厂实例。
摘要由CSDN通过智能技术生成

不使用Spring创建Bean实例,而是把Bean创建过程转移到开发者手中。

1. 静态工厂方法

//--创建工厂类
package com.erick.d1.hello;

public class StudentFactoryStatic {

    public static Student getStudent(String name){
        Student s = new Student();
        s.setName(name);
        return s;
    }
}
<!-- 配置中的class指向工厂类,factory-method指向工厂方法,若有参数是用 constructor-arg 元素传入 -->
<!-- 由工厂生产出的bean还可以继续配置依赖或者设置值,通过 property 标签来指定 -->

<bean id="student" class="com.erick.d1.hello.StudentFactoryStatic" factory-method="getStudent">
    <constructor-arg value="erick"></constructor-arg>
</bean>

2. 实例工厂方法

//--创建工厂类
package com.erick.d1.hello;

public class StudentFactoryInstance {

    public Student getStudent(String name){
        Student s = new Student();
        s.setName(name);
        return s;
    }
}
<!-- 配置中的factory-bean指向工厂类,factory-method指向工厂方法,若有参数是用 constructor-arg 元素传入 -->
<bean id="student" factory-bean="studentFactory" factory-method="getStudent">
    <constructor-arg value="erick"></constructor-arg>
</bean>

<bean id="studentFactory" class="com.erick.d1.hello.StudentFactoryInstance"/>

3. 说明

实例工厂需要spring来创建工厂对象。而静态工厂不需创建工厂对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值