Java Factory概念学习第四课(BeanFactory)

Java Factory概念学习第四课(BeanFactory)

beanFactory

今天引入Spring自带的factory即BeanFactory

先模拟beanFactory的工作原理:

    public interface Moveable {
      void run();
    }
public class Car implements Moveable{
  public void run() {
    System.out.println("奔跑中。。。。");
  }
}

模拟配置文件springtest.properties

VehicleType=com.beanfactory.Car

然后Test读取数据:

public class Test {

  public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    p.load(Test.class.getClassLoader().
        getResourceAsStream("com/beanfactory/springtest.properties"));
    String vehicleType = p.getProperty("VehicleType");
    System.out.println(vehicleType);
    Moveable m = (Moveable)Class.forName(vehicleType).newInstance();
    m.run();
  }

}

接下来看Spring究竟是怎么实现的,导包的过程省略:
在之前的基础上再加入一个Train类:

public class Train implements Moveable {

  @Override
  public void run() {
    System.out.println("火车况且况且");
  }

}

此时要将之前我们模拟spring的配置文件替换为spring的标准配置文件:

先编写标准的spring xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans>

  <bean id="v" class="com.springfactory.Train">
  </bean>
  
</beans>

之后改写Test类,启用spring的beanfactory方法:

public class Test {

  public static void main(String[] args) throws Exception {

    BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml");
    Object object = bf.getBean("v");
    Moveable m = (Moveable)object;
    m.run();
  }

}

以上就是初步的spring的BeanFactory

上一篇:抽象factory

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值