springIOC及Bean容器(2)

2016/1/15 11:39:07


1.接口

  • 用於溝通的中介物的抽象化
  • 實體把自己提供給外界的一種抽象化說明,用以由內部操作分離出外部溝通方法,使其能被修改內部而不影響外界其它實體與其交互的方式
  • 對應Java接口即聲明,聲明瞭哪些方法是對外公開提供的
  • 在Java8中,接口可以擁有方法體

2.面向接口編程

  • 結構設計中,分清層次及調用關係,每層只向外(上層)提供一組功能接口,各層間僅依賴接口而非實現類
  • 接口實現的變動不影響各層間的調用,這一點在公共服務中顯得尤爲重要
  • “面向接口編程”中的”接口”是用於隱藏具體實現和實現多態性的組件


    package com.zjx.interfaces;

    /**

    • @author acer
    • 接口聲明
      *
      */
      public interface IOneInterface {
      public String hello(String words);
      }

package com.zjx.interfaces.impl;

import com.zjx.interfaces.IOneInterface;

/**
 * @author acer
 * 被隱藏的接口實現類
 *
 */
public class OneInterfaceImpl implements IOneInterface {

    @Override
    public String hello(String words) {
        return "Word from interface\"IOneInterface\":"+words;
    }

}

package com.zjx.interfaces.test;

import com.zjx.interfaces.IOneInterface;
import com.zjx.interfaces.impl.OneInterfaceImpl;

public class Test {
    public static void main(String[] args) {
        IOneInterface iyf = new OneInterfaceImpl();
        System.out.println(iyf.hello("word..."));
    }
}

結果:Word from interface”IOneInterface”:word…

3.什麼是IOC

IOC:控制反轉,控制權的轉移,應用程序本身不負責依賴對象的創建和維護,而是由外部容器負責創建和維護,只是負責使用

DI(依賴注入):是其一種實現方式

目的:創建對象並且組裝對象之間的關係

業務對象進入Spring容器,通過配置的元數據,來生產出符合系統需要的對象

2004年,Martin Fowler探討了通過一個問題,既然IOC是控制反轉,那麼到底是“哪些方面的控制被反轉了呢?”,經過詳細的分析和論證後,他得出答案:“獲得依賴對象的過程被反轉了”。控制被反轉之後,獲得依賴對象的過程由自身管理變味了由IOC榮日主動注入。於是,他給控制反轉去了一個更合適的名稱叫做依賴注入(Dependency Injection)。他的答案實際上給出了實現IOC的方法,注入,所謂依賴注入,就是由IOC容器在運行期間,動態的將某種依賴關係注入到對象之中。

4.Spring的Bean配置

在Spring中,它把所有的對象都稱作爲Bean

Spring的配置有兩種:1.基於XML的配置;2.註解方式

<?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" 
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd 
                            http://www.springframework.org/schema/aop
                            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 

        <bean id="OneInterface" class="com.zjx.interfaces.impl.OneInterfaceImpl"></bean>


</beans>

5.單元測試

  • 下載junit-*.jar並引入工程
  • 創建UnitTestBase類,完成對Spring配置文件的加載/銷燬
  • 所有的單元測試類都繼承自UnitTestBase,通過它的getBean方法獲取想要得到的對象
  • 子類(具體執行單元測試的類)加註解:@RunWit(BlockJUnit4ClassRunner.class)
  • 單元測試方法加註解:@Test
  • 右鍵選擇要執行的單元測試方法執行或者執行一個類的全部單元測試方法

首先書寫UnitTestBase類

package com.zjx.interfaces.test;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;


public class UnitTestBase {
    /**
     * 相對路徑應用上下文
     */
    private ClassPathXmlApplicationContext context;

    /**
     * XML文件的存放路徑
     */
    private String springXmlPath;

    public UnitTestBase() {

    }

    public UnitTestBase(String springXmlPath){
        this.springXmlPath = springXmlPath;
    }
    @Before
    public void before(){
        if (StringUtils.isEmpty(springXmlPath)) {
            springXmlPath = "classpath*:spring-*.xml";
        }
        try {
            // xml文件用逗號或者空格符隔開,均可加載
            context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
            context.start();
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
    @After
    public void after(){
        context.destroy();
    }

    @SuppressWarnings("unchecked")
    protected <T extends Object> T getBean(String beanId){
        try {
            return(T)context.getBean(beanId);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected <T extends Object> T getBean(Class<T> clazz){
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }
}

測試上面的IOneInterface接口
package com.zjx.interfaces.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.zjx.interfaces.IOneInterface;

@RunWith(BlockJUnit4ClassRunner.class)
public class TestOneInterface extends UnitTestBase{

    public TestOneInterface() {
        // 通過父類構造方法傳入XML配置文件相對路徑
        super("classpath*:spring-ioc.xml");
    }

    @Test
    public void test(){
        IOneInterface oneInterface = super.getBean("oneInterface");
        System.out.println(oneInterface.hello("this is a test"));
    }
}

6.Bean容器初始化

  • 基礎:兩個包

    -org.springframework.beans

    -org.springframework.context

    -BeanFactory提供配置結構和基本功能,加載並初始化Bean

    -ApplicationContext保存了Bean對象並在Spring中被廣泛使用

  • 方式,ApplicationContext

    -本地文件

    -Classpath

    -Web應用中依賴servlet或Listener


在Web應用中的依賴

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-action.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章