Spring的核心机制依赖注入简介

http://tech.ddvip.com   2006年11月20日    社区交流

本文详细介绍Spring的核心机制依赖注入简介

//Chinese实现Person接口
public class Chinese implements Person
{
 //面向Axe接口编程,而不是具体的实现类
 private Axe axe;
 //默认的构造器
 public Chinese()
 {}
 //设值注入所需的setter方法
 public void setAxe(Axe axe)
 {
  this.axe = axe;
 }
 //实现Person接口的useAxe方法
 public void useAxe()
 {
  System.out.println(axe.chop());
 }
}

  Axe的第一个实现类

//Axe的第一个实现类 StoneAxe
public class StoneAxe implements Axe
{
 //默认构造器
 public StoneAxe()
 {}
 //实现Axe接口的chop方法
 public String chop()
 {
  return "石斧砍柴好慢";
 }
}

  下面采用Spring的配置文件将Person实例和Axe实例组织在一起。配置文件如下所示:

<!-- 下面是标准的XML文件头 -->
<?xml version="1.0" encoding="gb2312"?>
<!-- 下面一行定义Spring的XML配置文件的dtd -->
"http://www.springframework.org/dtd/spring-beans.dtd">
<!-- 以上三行对所有的Spring配置文件都是相同的 -->
<!-- Spring配置文件的根元素 -->
<BEANS>
 <!—定义第一bean,该bean的id是chinese, class指定该bean实例的实现类 -->
 <BEAN class=lee.Chinese id=chinese>
 <!-- property元素用来指定需要容器注入的属性,axe属性需要容器注入此处是设值注入,因此Chinese类必须拥有setAxe方法 -->
<property name="axe">
<!-- 此处将另一个bean的引用注入给chinese bean -->
<REF local="”stoneAxe”/">
</property>
</BEAN>
<!-- 定义stoneAxe bean -->
<BEAN class=lee.StoneAxe id=stoneAxe />
</BEANS>

  从配置文件中,可以看到Spring管理bean的灵巧性。bean与bean之间的依赖关系放在配置文件里组织,而不是写在代码里。通过配置文件的指定,Spring能精确地为每个bean注入属性。因此,配置文件里的bean的class元素,不能仅仅是接口,而必须是真正的实现类。

来源:csdn    责编:豆豆技术应用

正在加载评论...