---
title: "依赖注入入门-从dao到service"
author: "lbsnm"
date: "2011-11-23T18:30:10Z"
tags: ["Spring", "分层架构", "实验"]
categories: ["编程语言"]
slug: "dao-service"
draft: false
lastmod: "2011-11-23T21:31:54Z"
id: 1275274
url: "https://lbsnm.iteye.com/blog/1275274"
---

在分层的web应用系统中，通常将数据操作分为dao数据层和service业务逻辑层，[dao]()层负责对数据的操作，servlet或action通过service层对数据进行读写，而service层对数据的读写依赖于dao 层对数据的操作，因此存在着类之间的依赖。下面我们通过模拟实验理解不同技术对依赖关系的处理。

例1.在传统的模式中，依赖关系是通过构造对象的方式实现的。

创建如下三个类，模拟从dao到service的功能实现：

class dao\_class{

    public String selectUser(String user){

        return "找到了"+user;

    }

}

class service\_class{

    dao\_class dao=new dao\_class();

    public String findUser(String username){

        return dao.selectUser(username);

    }

}

public class dao\_service\_controller {

    public static void main(String \[]args)    {

        service\_class service=new service\_class();

        System.out.println(service.findUser("张三"));

    }

}

运行结果为：找到了张三。

程序中，语句：dao\_class dao=new dao\_class();使得service\_class严重“依赖”dao\_class，形成紧密的耦合关系，不符合现代编程理念。

例2.传统的通过接口方式减轻service\_class和dao\_class耦合程度。

interface dao\_interface{

    String selectUser(String user);

}

class dao\_class implements dao\_interface{

    public String selectUser(String user){

        return "找到了"+user;

    }

}

class service\_class implements service\_interface{

    dao\_interface dao;

    public void setDao(dao\_interface dao){

        this.dao=dao;

    }

    public String findUser(String username){

        return dao.selectUser(username);

    }

}

public class dao\_service\_controller {

    public static void main(String \[]args)    {

        service\_class service=new service\_class();

        dao\_interface dao=new dao\_class();

        service.setDao(dao);

        System.out.println(service.findUser("张三"));

    }

}

通过接口编程，方法：

public void setDao(dao\_interface dao){

        this.dao=dao;

    }

使得service\_class和dao\_class耦合程度大大降低，但是dao\_service中的语句：

dao\_interface dao=new dao\_class();

        service.setDao(dao);

使得dao\_service\_controller（模拟控制器）和dao\_class发生了依赖，因此这种方式也没有解决耦合紧密的问题。

例3. 在例2的基础上通过依赖注入的方式解决：

（1）首先在项目中添加spring库，如图（本例基于NetBeans7.0）：

 

![](http://dl.iteye.com/upload/attachment/593731/1fb8a986-35a8-367d-8fe0-f918aaf6c0c6.png)  
 

 

（2）新建“Spring XML配置文件”，命名为“mySpringCfg.xml”：

 

![](http://dl.iteye.com/upload/attachment/593733/dee932f7-555c-3481-8e54-6686aff62079.png)  
 

 

在步骤3中选择context的Spring名称空间：

 

![](http://dl.iteye.com/upload/attachment/593735/f8c7cb6f-1486-3a3f-9671-64117f825d74.png)  
 

 

（3）在mySpringCfg.xml文件中加入下面语句：

&lt;bean id="daoClass" class="dao\_class"/&gt;

    &lt;bean id="serviceClass" class="service\_class"&gt;

        &lt;property name="dao"&gt;

            &lt;ref local="daoClass"/&gt;

         &lt;/property&gt;

&lt;/bean&gt;

 

表示程序中有两个bean：daoClass和serviceClass，分别代表dao\_class 类和service\_class类，而“serviceClass”通过“接口”参数“dao”和“daoClass”发生依赖。

（4）修改dao\_service \_controller类：

public class dao\_service \_controller{

    public static void main(String \[]args)    {

           ApplicationContext ctx

=new FileSystemXmlApplicationContext("src/mySpringCfg.xml");

        service\_class service=(service\_class)ctx.getBean("serviceClass");

        System.out.println(service.findUser("张三"));

    }

}

其中语句：

ApplicationContext ctx=new FileSystemXmlApplicationContext("src/mySpringCfg.xml");

表示引入Spring XML配置文件：“mySpringCfg.xml”创建上下文ctx。

       语句：

service\_class service=(service\_class)ctx.getBean("serviceClass");

表示通过上下文ctx创建service\_class对象，在创建对象时，通过接口“dao”引用dao\_class对象，其关联语句分别为：

service\_class类中的语句：

dao\_interface dao;

    public void setDao(dao\_interface dao){

        this.dao=dao;

    }

注意接口成员的名称；

       配置文件mySpringCfg.xml中的语句：

       &lt;property name="dao"&gt;

            &lt;ref local="daoClass"/&gt;

     &lt;/property&gt;

 

其余的类和接口均不需要变动。可以看到，service\_class类只和接口dao\_interface成员dao发生关联，和dao\_Class类的依赖是通过配置文件发生的，是在创建对象时“注入”的。