FactoryBean 使用场景

官网地址: 1.8.3. Customizing Instantiation Logic with a FactoryBean

Core Technologiesicon-default.png?t=M666https://docs.spring.io/spring-framework/docs/5.2.22.RELEASE/spring-framework-reference/core.html#beans

概述

FactoryBean字面意思是工厂Bean。它就是起到一个工厂的作用。其getObject()方法可以生产另外一个对象,且生产的对象,也交由Spring容器管理。

通过FactoryBean的实现类,首字母小写,获得的是getObject返回的对象。在首字母小写前面加一个&符号,获得的是FactoryBean实例本身。

Spring提供了几个FactoryBean的实现类。用于在Spring的Bean中配置相应集合属性。

ListFactoryBean、MapFactoryBean、SetFactoryBean

示例代码

public class Computer {
    private String type;
    private String display;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDisplay() {
        return display;
    }

    public void setDisplay(String display) {
        this.display = display;
    }

    @Override
    public String toString() {
        return "Computer{" + "type='" + type + '\'' + ", display='" + display + '\'' + '}';
    }
}
/**
 * FactoryBean 的作用:通过ApplicationContext.getBean() 获取到的是Computer对象
 * 如果要获取Machine本身,在获取是用 & + id
 *
 * @see ListFactoryBean
 *
 */
public class Machine implements FactoryBean<Computer> {

    @Override
    public Computer getObject() throws Exception {
        Computer computer = new Computer();
        computer.setType("笔记本");
        computer.setDisplay("三星");
        return computer;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }
}
public class FactoryBeanDemo {
    public static void main(String[] args) {
        // 加载context.xml
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/context-factorybean.xml");
        Computer computer = context.getBean("machine", Computer.class);
        System.out.println(computer);
        //如果要获取Machine Bean本身
        Machine machine = context.getBean("&machine", Machine.class);
        System.out.println(machine);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

  <!-- bean definitions here -->
  <bean id="machine" class="org.xharvard.ioc.factorybean.Machine"/>
</beans>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值