依赖注入

控制翻转IoC(Inversion of Control):类中创建其他类的实力不用new来进行直接的调用,而是由Spring容器来完成,然后注入调用者,这就叫做控制翻转或者也可以称为依赖注入(DI).

 

其实说白了就是,我把我要用的东西我交给别人去做,而我直接用你做好的现成的东西。至于别人怎么做,我才不理会呢!

 

类中调用其他类的方法,必然会出现类之间的高度耦合,这对于现在一直希望实现低耦合来说肯定是不符合规范的,那我就去解耦合啊,交给谁干呢?Spring容器去干,这样就轻松的解决了这个问题。但是你想啊,Spring能做到,它为什么能做到,你想过没有?

 

我们来看一下下面的一个依赖注入的实例:

 

斧头接口Axe:

public interface Axe {
	public String chop();
}

 

斧头实现类SteelAxe和StoneAxe:

public class SteelAxe implements Axe{
	public SteelAxe(){
		
	}

	public String chop() {
		return "用钢斧头砍树好快啊";
	}
	
	
}

 

 

public class StoneAxe implements Axe{
	public StoneAxe(){
		
	}

	public String chop() {
		return "用石斧头砍树好慢啊";
	}
}

 

 

使用斧头的人接口:

public interface Person {
	public void useAxe();
}

 

子类:

public class Chinese implements Person{
	
	private Axe stoneAxe;
	private Axe steelAxe;
	public Chinese(){
		
	}
	
	public void useAxe() {
		System.out.println(stoneAxe.chop());
		System.out.println(steelAxe.chop());
	}

	public Axe getStoneAxe() {
		return stoneAxe;
	}

	public void setStoneAxe(Axe stoneAxe) {
		this.stoneAxe = stoneAxe;
	}

	public Axe getSteelAxe() {
		return steelAxe;
	}

	public void setSteelAxe(Axe steelAxe) {
		this.steelAxe = steelAxe;
	}
}

 

 

Bean配置文件MyXML.xml

 

<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="chinese" class="com.domain.Chinese">
		<property name="stoneAxe" ref="stoneAxe"></property>
		<property name="steelAxe" ref="steelAxe"></property>
	</bean>
	<bean id="stoneAxe" class="com.domain.StoneAxe"></bean>
	<bean id="steelAxe" class="com.domain.SteelAxe"></bean>
</beans>

Spring中最重要的就是Bean的配置信息。

我们可以看到配置文件中

bean中的属性: 

·id:表示实例化的对象的名称

·class:实例化的类(完整的包名)

 

bean的子属性property:

·name:实例化名称

·ref:使用的bean的id

 

执行类:

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

public class Exec {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx=new ClassPathXmlApplicationContext("MyXML.xml");
		Person p=(Person)ctx.getBean("chinese");
		p.useAxe();
	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值