1. 程式人生 > 其它 >4. Spring配置檔案 - Bean的依賴注入方式

4. Spring配置檔案 - Bean的依賴注入方式

我們之前寫的程式碼 只有實現業務邏輯層,實際MVC模式開發中 業務邏輯層 和 Dao【資料庫】層是一起用的,那麼在MVC開發模式中:

業務邏輯層裡面要呼叫Dao層,怎麼來獲取Bean呢? 我們寫個簡單的示範:【先來個MVC Service呼叫Dao 層的模擬:】

圖片可以看出 其中 介面都是 void show() 方法,

實現都是實現 show方法:

DAOIMPL:

   public void show() {
        System.out.println("HelloDaoImpl 的 show 方法.");
    }

SERVICEIMPL:

  public void
show() { System.out.println("HelloServiceImpl 的 show 方法."); }

Spring配置檔案:

<?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.xsd"
> <bean id="Dao" class="com.bihu.helloDaoImpl.HelloDaoImpl"></bean> <bean id="Service" class="com.bihu.helloServiceImpl.HelloServiceImpl"></bean> </beans>

然後我們改寫一下SERVICEIMPL,我們來呼叫DAO的實現:

package com.bihu.helloServiceImpl;

import com.bihu.helloDaoImpl.HelloDaoImpl;
import com.bihu.helloService.HelloService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloServiceImpl implements HelloService { /** * 相當於通過 Service的show方法呼叫Dao的show方法。 */ public void show() { ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); //獲取到Dao的Bean HelloDaoImpl dao = (HelloDaoImpl) app.getBean("Dao"); //呼叫HelloDaoImpl 中的 show dao.show(); } }

最後我們測試類,獲取到HelloServiceImpl的Bean,呼叫HelloServiceImol 的show 方法 方可 在內部又呼叫到了 HelloDaoImpl 的show方法:

import com.bihu.helloServiceImpl.HelloServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test {

    @Test //要匯入 Junit 的 GAV
    public void springTest(){
        ApplicationContext app =  new ClassPathXmlApplicationContext("applicationContext.xml");
        HelloServiceImpl service = (HelloServiceImpl)app.getBean("Service");
        service.show();
    }
}

執行結果:

資訊: Loading XML bean definitions from class path resource [applicationContext.xml]
HelloDaoImpl 的 show 方法.

所以說 這就是一個很簡單很簡單的一個傳遞呼叫而已。

待續。。。。。。。。。。。。