文章出處

Spring框架的核心功能之一就是控制反轉(Inversion of Control, IoC),也叫做依賴注入(dependency injection, DI)。關于依賴注入的具體內容可以參見Martin Fowler寫的一篇文章《Inversion of Control Containers and the Dependency Injection pattern》

Spring容器接口是BeanFactory,其提供了一些方法來配置和管理對象。ApplicationContext是BeanFactory的子接口,它集成了Spring的AOP特性,信息資源管理(用于全球化),公共事件等。簡單的說,BeanFactory提供了配置框架及基本的功能,而ApplicationContext增加了更多的企業級定制功能。比如其實現類WebApplicationContext可用于web應用程序中。

在Spring中,應用程序中受Spring IoC容器管理的對象叫做bean,即bean是一個由Spring IoC容器實例化、裝配及其它管理的對象。下圖是Spring IoC容器的一個簡單圖解。

以下列出了幾個常用的實現了ApplicationContext的容器對象。

  • AnnotationConfigApplicationContext :接收注解的class作為輸入來初始化配置。

  • GenericGroovyApplicationContext: 根據Groovy DSL來初始化配置。

  • ClassPathXmlApplicationContext:根據當前classpath下的xml文件初始化配置。

  • FileSystemXmlApplicationContext:根據文件系統路徑下的xml文件初始化配置。

Bean的定義有多種方式,XML定義,Annoation定義,Java代碼直接定義,Groovy DSL定義等。之前例子基本都演示過這些定義方法。

一個簡單的XML定義是這樣的。

1
2
3
4
5
6
7
8
9
10
<?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="movieService" class="huangbowen.net.service.DefaultMovieService”/>

</beans>

其包含一個id和一個class。id是一個bean的唯一標示,同一個spring容器中不能有兩個id一樣的bean,不過你也可以給bean起別名,使用name屬性即可,多個別名可以用逗號,分號或空格分開。

1
<bean id="movieService" name="service1 service2" class="huangbowen.net.service.DefaultMovieService"/>
1
<bean id="movieService" name=“service1,service2" class="huangbowen.net.service.DefaultMovieService"/>
1
<bean id="movieService" name="service1;service2" class="huangbowen.net.service.DefaultMovieService"/>

也可以使用alisa來起別名。

1
2
3
<bean id="movieService" name="service1,service2" class="huangbowen.net.service.DefaultMovieService"/>

<alias name="movieService" alias="service3"/>

如果你的bean的實例不是通過構造函數直接生成的,而是通過工廠方法生成那,那么也有相應的配置方法。

1
<bean id="defaultMovieService" class="huangbowen.net.service.MovieServiceFactory" factory-method="GetMovieService" />
MovieServiceFactory
1
2
3
4
5
6
7
8
9
10
package huangbowen.net.service;

public class MovieServiceFactory {

    private static DefaultMovieService defaultMovieService = new DefaultMovieService();

    public static MovieService GetMovieService() {
        return defaultMovieService;
    }
}

如果bean對象是由一個實例工廠生成的,那么應該這樣配置。

1
2
3
    <bean id="serviceLocator" class="huangbowen.net.service.MovieServiceLocator"/>

    <bean id="instantMovieService" factory-bean="serviceLocator" factory-method="GetMovieService"/>
MovieServiceLocator
1
2
3
4
5
6
7
8
9
10
package huangbowen.net.service;

public class MovieServiceLocator {

    private static DefaultMovieService defaultMovieService = new DefaultMovieService();

    public MovieService GetMovieService() {
        return defaultMovieService;
    }
}

本例中的源碼請在我的GitHub上自行下載。


文章列表


不含病毒。www.avast.com
創作者介紹
創作者 IT工程師數位筆記本 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣( 26 )