Spring IOC简单实例

本文通过一个简单示例介绍了Spring框架中IOC容器的基本用法。示例中定义了一个HuMan接口及其实现类Chinese和American,分别展示了中国人和美国人在吃饭和走路方面的不同习惯。通过Spring的配置文件,实现了对象的创建和依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 把对类的实例化工作从类内部转交给Spring的IOC容器来做,被称为控制反转。下面是一个最简单的实例。

 

 这是一个接口,定义了吃饭和走路两个方法:

 

package com.spring.test.manager;

public interface HuMan {
	
	public void eat();// 次方法用来吃
	public void walk();//此方法用来走路
	
}

 下面是两个实现类:

package com.spring.test.manager.impl;
import com.spring.test.manager.HuMan;
public class Chines implements HuMan {

	public Chines() {
		
	}

	public void eat() {
		System.out.println("中国人对吃很有一套!!");

	}
	public void walk() {
		System.out.println("中国人走路很快!!");

	}

}
 
package com.spring.test.manager.impl;
import com.spring.test.manager.HuMan;
public class Amrican implements HuMan {

	
	public Amrican() {
		
	}

	public void eat() {
		System.out.println("美国人喜欢吃面包!!!!");
	}

	
	public void walk() {
		System.out.println("美国人喜欢开车,不喜欢走路!");
	}

}

 下面是配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	
	<bean id="china" class="com.spring.test.manager.impl.Chines"/>
	<bean id="usa" class="com.spring.test.manager.impl.Amrican"/>
	
</beans>

 下面是测试的代码

package com.spring.test.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.spring.test.manager.HuMan;

public class TestClass {

	public TestClass() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
ApplicationContext appContext=new FileSystemXmlApplicationContext("/src/applicationContext.xml");
		HuMan huMan=null;
		huMan= (HuMan) appContext.getBean("china");
		huMan.eat();
		huMan.walk();
		
		huMan=(HuMan)appContext.getBean("usa");
		huMan.eat();
		huMan.walk();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值