【Spring笔记】工厂bean

机器人

public class Robot {
    Robot(){
        System.out.println("有只机器人被创建了");
    }
}

工厂bean有两种

①静态方法生产对象

②普通方法生产对象

===========①=============

静态方法机器人工厂

public class RobotFactory {
    public static Robot getRobot(){
        System.out.println("机器人工厂生产机器人中……");
        return new Robot();
    }
}

注册为bean

<bean class="org.example.entity.RobotFactory" factory-method="getRobot"></bean>

(此时不能再注册Robot类的bean,否则在使用getBean(Robot.class)时,spring将不知道调用哪个bean)

Main函数中运行

ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
Robot r1 = context.getBean(Robot.class);

可以直接由上面的工厂bean获得Robot对象

==============②=============

普通方法机器人工厂

public class RobotFactory {
    public Robot getRobot(){
        System.out.println("机器人工厂生产机器人中……");
        return new Robot();
    }
}

这种情况只能先把RobotFactory注册为bean,再注册一个bean,在此bean中指定factory-bean属性,属性值即为RobotFactory的bean的名字,同时在factory-method属性中指定getRobot方法。

因此需要给RobotFactory添加name属性,不然Robot不知道他的工厂bean叫什么名字

<bean class="org.example.entity.RobotFactory" name="RobotFactoryBean" ></bean>
<bean factory-bean="RobotFactoryBean" factory-method="getRobot" ></bean>

同方法①使用getBean(Robot.class)获得Robot实例

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值