Spring IoC

 

1、在项目根目录下创建一个bean.xml文件

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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

       <bean id="Chinese" class="cn.com.chengang.spring.Chinese"/>

       <bean id="American" class="cn.com.chengang.spring.American"/>

</beans>

2、修改ClientTest程序如下:

package cn.com.chengang.spring;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ClientTest {

    public final static String CHINESE = "Chinese";

    public final static String AMERICAN = "American";

 

    public static void main(String[] args) {

        //        Human human = null;

        //        human = new Factory().getHuman(Factory.CHINESE);

        //        human.eat();

        //        human.walk();

        //        human = new Factory().getHuman(Factory.AMERICAN);

        //        human.eat();

        //        human.walk();

 

        ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml");

        Human human = null;

        human = (Human) ctx.getBean(CHINESE);

        human.eat();

        human.walk();

        human = (Human) ctx.getBean(AMERICAN);

        human.eat();

        human.walk();

    }

}

从这个程序可以看到,ctx就相当于原来的Factory工厂,原来的Factory就可以删除掉了。然后又把Factory里的两个常量移到了ClientTest类里,整个程序结构基本一样。

再回头看原来的bean.xml文件的这一句

<bean id="Chinese" class="cn.com.chengang.spring.Chinese"/>

id就是ctx.getBean的参数值,一个字符串。class就是一个类(包名+类名)。然后在ClientTest类里获得Chinese对象就是这么一句

human = (Human) ctx.getBean(CHINESE);

因为getBean方法返回的是Object类型,所以前面要加一个类型转换。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值