<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>


    posts - 15,  comments - 34,  trackbacks - 27

    October 2003

    You may have heard the buzz this summer around the Spring Framework. In this article, I’ll try to explain what Spring sets out to achieve, and how I believe it can help you to develop J2EE applications.
    在這個夏天,你可以聽到許許多多圍繞著Spring Framework的聲音. 這篇文章,我將說明Spring 的作用和如何幫助你開發J2EE應用.

    Yet another framework?
    哦,又一個框架?

    You may be thinking \\\\\\\"not another framework.\\\\\\\" Why should you bother to read this article, or download the Spring Framework, when there are already many open source (and proprietary) J2EE frameworks?
    你也許正在想\\\\\\\"不,又一個框架\\\\\\\". 在眾多的開源J2EE框架橫行的時代,為什么你還會去讀這篇文章或者下載Spring Framework?

    I believe that Spring is unique, for several reasons:
    我相信Sping 的獨特,有下列原因:

    * It addresses areas that many other popular frameworks don’t. Spring focuses around providing a way to manage your business objects.
    * Spring 的地址區域? 是其他框架所不具備的. Spring 只圍繞一點,那就是管理業務對象.

    * Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation, yet its architecture is internally consistent. So you get maximum value from your learning curve. You might choose to use Spring only to simplify use of JDBC, for example, or you might choose to use Spring to manage all your business objects.
    * Spring 非常的全面和標準. Spring是一個分層構架,意思是你可以選擇只用它的一部分,而不影響其他.它的構架體系是內部相容的.所以,你將會在你的學習曲線中獲得最大價值.
    例如,你可以選擇只用Spring 的JDBC 單一應用 或者 用Spring 管理你的業務對象.

    * It’s designed from the ground up to help you write code that’s easy to test. Spring is an ideal framework for test driven projects.
    * Spring的設計可以幫助你從表層到簡單地寫出測試代碼.Spring是一個理想的測試驅動項目的框架.

    Spring is not necessarily one more framework dependency for your project. Spring is potentially a one-stop shop, addressing most infrastructure concerns of typical applications. It also goes places other frameworks don’t.
    在你的項目中,Spring 不必依靠更多的框架. Spring 相當于一個一站式商店,從事更多的涉及典型應用的基礎框架.它也不必替換任何框架.


    Although it has been an open source project only since February 2003, Spring has a long heritage. The open source project started from infrastructure code published with my book, Expert One-on-One J2EE Design and Development, in late 2002. Expert One-on-One J2EE also laid out the basic architectural thinking behind Spring. However, the architectural concepts go back to early 2000, and reflect my experience in developing infrastructure for a series of successful commercial projects.
    雖然Spring 是一個起始于2003年2月的一個開源項目,但是它有很長時間的傳統. 這個開源項目開始于(2002年出版)
    發布的基礎編碼, 這本書同樣也展示了在Spring之后的基礎構架. 然而,這個構架的觀念在2000年就誕生了, 而且源自我長時間從事一連串的商業項目的成功開發經驗.


    Since January 2003, Spring has been hosted on SourceForge. There are now ten developers, of whom six are highly active.
    自從2003年一月份,Spring 在SourceForge上被建立起來. 現在有10名開發人員,6名高手.


    Architectural benefits of Spring
    Spring 構架優勢

    Before we get down to specifics, let’s look at some of the benefits Spring can bring to a project:
    在我們詳細說明之前,讓我們先看一下Spring 可以給一個項目帶來的好處:

    * Spring can effectively organize your middle tier objects, whether or not you choose to use EJB. Spring takes care of plumbing that would be left up to you if you use only Struts or other frameworks geared to particular J2EE APIs.
    *Spring 可以有效的組織你的中間層對象,無論你是否選擇了EJB. 如果你只用了Struts 或者其他框架來連接特定的J2EE APIs,Spring 更關心的是委托到你的管道?


    * Spring can eliminate the proliferation of Singletons seen on many projects. In my experience, this is a major problem, reducing testability and object orientation.
    * Spring 可以消除一個單獨項目看起來像多個項目的擴散. 以我的經驗, 主要的問題是, 減弱了測試能力和對象方位.

    * Spring can eliminate the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. Ever wondered what magic property keys or system properties a particular class looks for, and had to read the Javadoc or even source code? With Spring you simply look at the class’s JavaBean properties. The use of Inversion of Control (discussed below) helps achieve this simplification.
    * Spring 可以消除規定多樣的定制屬性文件的需要, 用一致的配置操作貫穿這個應用和項目.多樣的屬性健或者系統屬性尋找使你不得不去讀Javadoc 或者甚至是源代碼?然而, Sping可以使你非常簡單地看到這些class 的 JavaBean的屬性. 控制的倒置用法(下面介紹)可以幫助你完成簡化.

    * Spring can facilitate good programming practice by reducing the cost of programming to interfaces, rather than classes, almost to zero.
    * Spring 可以使良好的編程習慣更容易培養,利用接口代替classes 減弱編程成本,降至最小.

    * Spring is designed so that applications built with it depend on as few of its APIs as possible. Most business objects in Spring applications have no dependency on Spring.
    * Spring 的設計使依靠很少的APIs 建立應用成為可能. 在Spring 應用中的許多業務對象根本不要依靠Spring.

    * Applications built using Spring are very easy to unit test.
    * 利用Sping 建立的應用使單元測試變得非常簡單.

    * Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code.
    * Spring 是使用EJB成為一個選擇,優于成為決定性的應用構架 .你可以選擇作為POJOs 或者 local EJBs 擴展業務借口,而不影響調用代碼.

    * Spring helps you solve many problems without using EJB. Spring can provide an alternative to EJB that’s appropriate for many web applications. For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA implementation, if you only need to work with a single database.
    * Spring 可以幫助你解決沒有EJB的許多的問題.Spring 提供了為多個web 應用選擇性適當的JEB.例如, Spring 可以用 AOP 去傳遞聲明事務管理,在不用EJB容器的情況下.
    如果你只需要工作在單個的數據庫上面, 甚至不用JTA 的支持.

    * Spring provides a consistent framework for data access, whether using JDBC or an O/R mapping product such as Hibernate.
    * Spring 提供了堅固的數據存儲框架, 無論用JDBC 或者 像Hibernate 一樣的 O/R mapping 產品.

    Spring really can enable you to implement the simplest possible solution to your problems. And that’s worth a lot.
    Spring 確實是你程序擴展簡單的方案.并且具有相當大的價值.

    What does Spring do?
    Spring 做什么呢?

    Spring provides a lot of functionality, so I’ll quickly review each major area in turn.
    Spring 具有很多的功能, 我們可以快速瀏覽每個主要的范圍.

    Mission statement
    任務描述

    Firstly, let’s be clear on Spring’s scope. Although Spring covers a lot of ground, we do have clear vision as to what it should and shouldn’t address.
    首先, 讓我們跳出Spring. 雖然Spring 覆蓋了很多的層面, 我們必須清楚了解他做什么不做什么.

    Spring’s main aim is to make J2EE easier to use and promote good programming practice.
    Spring 的主要目標是使J2EE更簡單易用, 促進良好的編程習慣.

    Spring does not reinvent the wheel. Thus you’ll find no logging packages in Spring, no connection pools, no distributed transaction coordinator. All these things are provided by open source projects (such as Commons Logging, which we use for all our log output, or Commons DBCP), or by your application server. For the same reason, we don’t provide an O/R mapping layer. There are good solutions to this problem such as Hibernate and JDO.
    Spring 遵守不重新發明輪子的原則. 因此,你在Spring 找不到 日志管理, 連接池,分布事務調節的程序包. 所有這些功能可以由開源項目(如,Commons Logging ,Common DBCP)提供,
    或者是你的應用服務器. 同樣的原因, 我們不提供O/R mapping 層, 因為已經有很好地解決方案, 如,Hibernate 和 JDO.


    Spring does aim to make existing technologies easier to use. For example, although we are not in the business of low-level transaction coordination, we do provide an abstraction layer over JTA or any other transaction strategy.
    Spring 主要目標是讓已經存在的技術更簡單易用. 例如,雖然我們沒有低級的事務調節業務,但是我們提供了在JTA 或者其他事物級別處理之上的提取層.

    Spring doesn’t directly compete with other open source projects unless we feel we can provide something new. For example, like many developers, we have never been happy with Struts, and feel that there’s room for improvement in MVC web frameworks. In some areas, such as its lightweight IoC container and AOP framework, Spring does have direct competition, but these are areas in which no solution has become popular. (Spring was a pioneer in these areas.)
    Spring
    Spring 沒有直接和其他的開源項目進行競爭除非我們認為我們提供了新的功能. 例如, 像很多開發者一樣,我們一直對strus感覺不好,是因為它把我們框在了它提供了MVC框架之中.
    在某些地方,像輕巧的IoC 容器和AOP 框架,Spring 將和他們有著直接的競爭, 但是在這些區域還沒有形成普遍成型的方案(Spring 是這個區域的先驅)

    Spring also benefits from internal consistency. All the developers are singing from the same hymn sheet, the fundamental ideas remaining faithful to those of Expert One-on-One J2EE Design and Development. And we’ve been able to use some central concepts, such as Inversion of Control, across multiple areas.
    Spring 同樣獲益于區域一致性. 就像所有的開發者唱著同樣的贊美詩一樣,大家都支持Expert One-on-One J2EE Design and Development . 并且我們都用一些主要的概念,
    倒置控制,穿越多個區域.

    Spring is portable between application servers. Of course ensuring portability is always a challenge, but we avoid anything platform-specific or non-standard, and support users on WebLogic, Tomcat, Resin, JBoss, WebSphere and other application servers.

    Spring 可以輕巧的用于應用服務器. 當然, 保證輕巧的能力一直是一個挑戰,但是, 我們避免任何平臺詳細或者不標準, 并且支持于Weblogic ,Tomcat ,Resin, JBoss, WebSphere 和其他的應用服務器.

    Inversion of control container
    控制容器的倒置

    The core of Spring’s design is the org.springframework.beans package, designed for working with JavaBeans. This package typically isn’t used directly by users, but serves as the underpinning of much of the other functionality.
    Spring的設計核心是 org.springframework.beans 包, 設計協調JavaBeans的工作. 這個包代表可以直接被用戶使用, 但是可以作為其他很多功能的基礎服務.

    The next higher layer of abstraction is the \\\\\\\"Bean Factory.\\\\\\\" A Spring bean factory is a generic factory that enables objects to be retrieved by name, and which can manage relationships between objects.
    下一個較高的層面是\\\\\\\"Bean Factory\\\\\\\", 一個Spring bean factory 是一個通常可以管理連接多個對象且可以根據name重新獲得對象的factory。

    Bean factories support two modes of objects:
    Bean factories 支持兩種對象模式:

    * \\\\\\\"Singleton\\\\\\\": in this case, there’s one shared instance of the object with a particular name, which will be retrieved on lookup. This is the default, and most often used, mode. It’s ideal for stateless service objects.
    * 單粒模式: 在這里,有一個共享具有特使名稱的對象實例,它將可以被找回. 這是一個缺省模式, 而且是應用最為廣泛德模式.這種模式是理想的無狀態服務對象.

    * \\\\\\\"Prototype\\\\\\\": in this case, each retrieval will result in the creation of an independent object. For example, this could be used to allow each user to have their own object.
    * \\\\\\\"原型模式\\\\\\\": 在這里,每一個獲得導致一個獨立的對象創立, 例如,這可以用于允許用戶使用他們自己的對象.

    As org.springframework.beans.factory.BeanFactory is a simple interface, it can be implemented for a range of underlying storage methods. You could easily implement your own, although few users find they need to. The most commonly used BeanFactory definitions are:
    因為 org.springframwork.beans.factory.BeanFactory是一個簡單的接口, 它可以被潛在的存儲方法行列執行?. 雖然,很少用戶需要,但是這可以使你可以簡單的拓展你自己 . 一些通常用于BeanFactory 定義是:

    * The XmlBeanFactory. This parses a simple, intuitive XML structure defining the classes and properties of named objects. We provide a DTD to make authoring easier.
    * XmlBeanFactory. 這是一個簡單的解析器.根據XML 結構定義classes和命名對象的屬性. 我們提供了一個DTD來使命名更加得簡單.

    * ListableBeanFactoryImpl: This provides the ability to parse bean definitions in properties files, and create BeanFactories programmatically.
    * ListableBeanFactoryImpl: 這提供了在屬性文件里面解析bean定義的能力,和編寫創建BeanFactories.

    Each bean definition can be a POJO (defined by class name and JavaBean initialisation properties), or a FactoryBean. The FactoryBean interface adds a level of indirection. Typically this is used to create proxied objects using AOP or other approaches: for example, proxies that add declarative transaction management. (This is similar to EJB interception in concept, but works out much simpler in practice.)
    每個bean的定義可以是一個POJO(定義class和JavaBean初始化屬性), 或者一個FactoryBean. FactoryBean 接口添加了一個間接層.代表了這將用于創建用于AOP或者其他途徑的
    代理對象:例如, 加入聲明事務管理的代理.(這是一個類似于EJB偵聽的概念,但是在實踐中實現十分的簡單)

    BeanFactories can optionally participate in a hierarchy, \\\\\\\"inheriting\\\\\\\" definitions from their ancestors. This enables the sharing of common configuration across a whole application, while individual resources such as controller servlets also have their own independent set of objects.
    BeanFactories 可以在一個層面上進行隨意的添加,根據他們的原先的定義. 這能夠通過基礎配置的共享穿過整個應用,當個別資源如controller servlets也設置自己為單個的對象.

    This motivation for the use of JavaBeans is described in Chapter 4 of Expert One-on-One J2EE Design and Development, which is available on the ServerSide as a free PDF (http://www.theserverside.com/res ... dJohnsonInterview).
    這是為了聲明JavaBeans的用法,在第四章,用法在ServerSide的免費PDF(http://www.theserverside.com/res ... dJohnsonInterview).

    Through its BeanFactory concept, Spring is an Inversion of Control container. (I don’t much like the term container, as it conjures up visions of heavyweight containers such as EJB containers. A Spring BeanFactory is a container that can be created in a single line of code, and requires no special deployment steps.)
    通過它的BeanFactory 概念,Spring 作為一個控制容器的倒置.(我非常不喜歡期限容器,因為它依靠重量級的容器,如EJB容器).Spring BeanFactory是一個可以在一行代碼中創建的容器,而且不需要特殊的部署)


    The concept behind Inversion of Control is often expressed in the Hollywood Principle: \\\\\\\"Don’t call me, I’ll call you.\\\\\\\" IoC moves the responsibility for making things happen into the framework, and away from application code. Where configuration is concerned this means that while in traditional container architectures such as EJB, a component might call the container to say \\\\\\\"where’s object X, which I need to do my work\\\\\\\", with IoC the container figures out that the component needs an X object, and provides it to it at runtime. The container does this figuring out based on method signatures (such as JavaBean properties) and, possibly, configuration data such as XML.
    控制倒置(IoC)這個感念是經常在好萊塢原則上使用:\\\\\\\"不要打電話給我,我打給你\\\\\\\".IoC的責任是記錄進入framework 發生的事件,并且遠離應用代碼. 涉及到配置的地方,也就是說,
    像EJB一樣傳統的容器構架,一個組建可以調用容器,并且說\\\\\\\"哪兒有可以讓我工作的Object X\\\\\\\",對于IoC容器判斷出這個組建需要 X 對象,并且在運行的時候提供它執行.容器在方法
    簽名(就像JavaBean屬性)上作出這個基礎的判斷,并且,盡可能的,配置數據,如XML一樣.

    IoC has several important benefits. For example:
    控制倒置的幾個優勢,例如:

    * Because components don’t need to look up collaborators at runtime, they’re much simpler to write and maintain. In Spring’s version of IoC, components express their dependency on other components via exposing JavaBean setter methods. The EJB equivalent would be a JNDI lookup, which requires the developer to write code.
    * 因為組件不需要在運行時間尋找合作,所以他們可以很容易的編寫和維護. 在Spring的IoC版本里面, 組件表述了他們通過JavaBean的setter方法來被其他組件支持. 這等于EJB中
    通過JNDI lookup,開發人員寫的請求代碼.

    * For the same reasons, application code is much easier to test. JavaBean properties are simple, core Java and easy to test: just write a self-contained JUnit test method that creates the object and sets the relevant properties.
    * 為了同樣的原因,應用代碼變得非常容易測試.JavaBean屬性簡單,主要的程序測試也變得容易: 剛剛寫了一個包含自己的創建對象和設置關聯屬性的JUnit測試方法.

    * A good IoC implementation preserves strong typing. If you need to use a generic factory to look up collaborators, you have to cast the results to the desired type. This isn’t a major problem, but it is inelegant. With IoC you express strongly typed dependencies in your code and the framework is responsible for type casts. This means that type mismatches will be raised as errors when the framework configures the application; you don’t have to worry about class cast exceptions in your code.
    * 一個良好的IoC執行保持健壯的輸入. 如果你需要用一般的factory尋找合作者,你不得不造型結果成你需要的類型.這不是一個主要的程序,但是這是不好的.對于IoC 你需要在你的
    代碼 和框架響應里為輸入造型傳遞健壯的信任類型. 這意味著在配置應用的時候輸入機制將可能存在錯誤;但是不必擔心造型異常.

    * Most business objects don’t depend on IoC container APIs. This makes it easy to use legacy code, and easy to use objects either inside or outside the IoC container. For example, Spring users often configure the Jakarta Commons DBCP DataSource as a Spring bean: there’s no need to write any custom code to do this. We say that an IoC container isn’t invasive: using it won’t invade your code with dependency on its APIs. Any JavaBean can become a component in a Spring bean factory.
    * 許多業務對象不依靠IoC. 這使簡化為使用繼承代碼,并且簡單用于IoC容器的內部和外部.例如,Spring 用戶通常配置Commons DBCP 數據源作為Spring bean:這不需要寫任何
    代碼就可以完成. 我們說IoC容器不會影響:利用APIs用它將不會影響你的代碼. 任何JavaBean可以成為Spring bean factory 的一個組件.

    This last point deserves emphasis. IoC is unlike traditional container architectures, such as EJB, in this minimization of dependency of application code on container. This means that your business objects can potentially be run in different IoC frameworks - or outside any framework - without code changes.
    最后要強調的是,IoC 不同于傳統的容器構架,如:EJB, 應用最小限度的依靠容器. 這意味著你的業務對象可以潛在的運行在不同的IoC 框架上-或者沒有框架-而不需要改動任何代碼.

    In my experience and that of Spring users, it’s hard to overemphasize the benefits that IoC brings to application code.
    最為Spring用戶的經驗,這里強調了IoC給你的代碼帶來的好處.

    IoC is not a new concept, although it’s only just made prime time in the J2EE community. There are alternative IoC containers: notably, Apache Avalon, PicoContainer and HiveMind. Avalon has never become particularly popular, although it is powerful and has a long history. Avalon is fairly heavyweight and complex, and seems more invasive than newer IoC solutions. PicoContainer is lightweight and emphasizes the expression of dependencies through constructors rather than JavaBean properties. Unlike Spring, its design allows the definition of only one object of each type (possibly a limitation resulting from its rejection of any metadata outside Java code). For a comparison between Spring and PicoContainer and other IoC frameworks, see the article \\\\\\\"The Spring Framework - A Lightweight Container\\\\\\\" on the Spring website at http://www.springframework.org/docs/lightweight_container.html. This page includes a link to the PicoContainer website.
    IoC不是一個新的概念,但是它在J2EE團體里面剛剛成為精華. 有那些IoC 容器可選呢: notably, Apache Avalon, PicoContainer 和 HiveMind.Avalon 不會成為通用,雖然它很強大
    而且有很長的歷史.Avalon 相當的重量級和復雜,并且看起來比新的IoC解決方案更內聚. PicoContainer是一個輕量級而且強調通過構造器傳遞優于JavaBean 屬性. 不像Spring,
    它涉及允許定義一個對象多種輸入(可能局限于外部的java code收集結果), 作為比較http://www.springframework.org/docs/lightweight_container.html. 這個業面包含了
    PicoContainer站點.

    Spring BeanFactories are very lightweight. Users have successfully used them inside applets, as well as standalone Swing applications. (They also work fine within an EJB container.) There are no special deployment steps and no detectable startup time. This ability to instantiate a container almost instantly in any tier of an application can be very valuable.
    Spring BeanFactories 是非常輕型的.用戶可以成功地在applets里面使用,作為獨立的Swing應用.(它們也在EJB容器工作的很好) 沒有制定的部署步驟和省去了重起的時間.這個能力
    表明一個容器在應用的任何層面差不多立即可以發揮重大的價值.

    The Spring BeanFactory concept is used throughout Spring, and is a key reason that Spring is so internally consistent. Spring is also unique among IoC containers in that it uses IoC as a basic concept throughout a full-featured framework.
    Spring BeanFactory 概念應用于Spring, 而且是Spring中心協調的關鍵原因. Spring 也是在IoC容器中唯一利用基礎概念完成全部特點的框架.

    Most importantly for application developers, one or more BeanFactories provide a well-defined layer of business objects. This is analogous to, but much simpler than, a layer of local session beans. Unlike EJBs, the objects in this layer can be interrelated, and their relationships managed by the owning factory. Having a well-defined layer of business objects is very important to a successful architecture.
    許多應用開發者關心的,一個或者多個BeanFactories可以提供了一個定義好的業務對象層. 這類似,且非常簡單,一個本地session beans的一個層. 不同于EJBs, 在這個層里面的對象
    是相關的,并且他們的關系被自己的factory 管理.提供一個定義完好的業務對象層是成功構架非常重要的一點.

    A Spring ApplicationContext is a subinterface of BeanFactory, which provides support for:
    Spring ApplicationContext 是BeanFactory的子接口,為下列提供支持:

    * Message lookup, supporting internationalization
    * 消息尋找,支持國際化

    * An eventing mechanism, allowing application objects to publish and optionally register to be notified of events
    * 事件機制,允許應用對象發布和操作注冊成為事件

    * Portable file and resource access
    * 輕巧的文件和資源存儲

    In the following example, we use a BasicDataSource from the Jakarta Commons DBCP project. This class (like many other existing classes) can easily be used in a Spring bean factory, as it offers JavaBean-style configuration. The close method that needs to be called on shutdown can be registered via Spring\\\\\\\'s \\\\\\\"destroy-method\\\\\\\" attribute, to avoid the need for BasicDataSource to implement any Spring interface.
    在下面的例子里,我們用一個DBCP項目中的BasicDataSource 。這個class(和其他存在的class一樣)可以簡單的在Spring bean factory使用,并且提供了JavaBean配置。這種需要在shutdown的時候被調用的精密方法可以通過Spring的\\\\\\\"destroy-method\\\\\\\"屬性被注冊,而且提供了需要為BasicDataSource執行的許多Spring 接口。


    代碼:


    destroy-method=\\\\\\\"close\\\\\\\">

    com.mysql.jdbc.Driver


    jdbc:mysql://localhost:3306/mydb

    root

     

    All the properties of BasicDataSource we e interested in are Strings, so we specify their values with the element. Spring uses the standard JavaBean PropertyEditor mechanism to convert String representations to other types if necessary.
    我們感興趣的是Strings ,BasicDataSource的所有屬性,所以我們用標簽指定了他們的值。如果必要的話,Spring 用標準的JavaBean屬性編輯機制來轉換String 表示其他的類型.
    Now we define the DAO, which has a bean reference to the DataSource. Relationships between beans are specified using the element:
    現在,我們定義這個用一個bean 表示為DataSource的 DAO. 用標簽來表示beans之間的關系:

    代碼:
    class=\\\\\\\"example.ExampleDataAccessObject\\\\\\\">


    The business object has a reference to the DAO, and an int property (exampleParam):
    這個業務對象涉及到DAO,并且有一個int屬性(exampleParam):

    代碼:
    class=\\\\\\\"example.ExampleBusinessObject\\\\\\\">

    10

    Relationships between objects are normally set explicitly in configuration, as in this example. We consider this to be a Good Thing. However, Spring also provides what we call \\\\\\\"autowire\\\\\\\" support, a la PicoContainer, where it figures out the dependencies between beans. The limitation with this - as with PicoContainer - is that if there are multiple beans of a particular type it impossible to work out which instance a dependency of that type should be resolved to. On the positive side, unsatisfied dependencies can be caught when the factory is initialized. (Spring also offers an optional dependency check for explicit configuration, which can achieve this goal.)
    這兩個對象的關系可以在配置中非常清楚,有如例子一樣。我們認為這樣做很好.無論如何,Spring也提供了我們叫做\\\\\\\"autowire\\\\\\\"的支持, 一個la PicoContainer,它可以判斷這兩個beans只見的依賴關系.PicoContainer的局限性是如果有多個的Beans有特殊的類型,這種類型不可能完全解決實例的類型可以判斷之間的依賴關系.值得一提的是,不能班組的依賴關系可以在factory初始化的時候被捕獲.(Spring 也提供一種可以完成這個目標的的外部配置)
    We could use the autowire feature as follows in the above example, if we didn\\\\\\\'t want to code these relationships explicitly:
    在以上的例子里,我們可以用autowire 用來理解,如果我們不想編碼這些外部關系:
    代碼:
    class=\\\\\\\"example.ExampleBusinessObject\\\\\\\"
    autowire=\\\\\\\"byType\\\\\\\">

    10

    With this usage, Spring will work out that the dataSource property of exampleBusinessObject should be set to the implementation of DataSource it finds in the present BeanFactory. It‘s an error if there is none, or more than one, bean of the required type in the present BeanFactory. We still need to set the exampleParam property, as it\\\\\\\'s not a reference.
    對于這個用法,Spring 將可以理解為exampleBusinessObject的dataSource 屬性在父BeanFactory里找到DataSource,將其設置執行.如果在beanFactory沒找到或者多于一個請求類型的bean產生一個error。我們還需要設置exampleParam屬性,因為它沒有參數.

    Autowire support and dependency checking is presently in CVS and will be available in Spring 1.0 M2 (due October 20, 2003). All other features discussed in this article are in the current 1.0 M1 release.
    Autowire支持和依賴關系檢查是剛剛加入CVS和將發布在Spring 1.0 M2(10/20,2003).所有其他的特點討論當前1.0 M1發布版本.

    Externalizing relationships from Java code has an enormous benefit over hard coding it, as it possible to change the XML file without changing a line of Java code. For example, we could simply change the myDataSource bean definition to refer to a different bean class to use an alternative connection pool, or a test data source. We could use Spring JNDI location FactoryBean to get a datasource from an application server in a single alternative XML stanza.
    具體的說,這樣描述關系比硬編碼有很大的好處,因為只改變XML文件而不用改變java 代碼.例如,我們可以簡單的改變myDataSource bean 定義提供不同的bean class 用選擇性的連接池,或者一個測試數據源. 我們用Spring JNDI本地FactoryBean從application server兩個單獨的選擇性節點得到一個數據源.
    Now let\\\\\\\'s look at the Java code for the example business object. Note that there are no Spring dependencies in the code listing below. Unlike an EJB container, a Spring BeanFactory is not invasive: you don\\\\\\\'s normally need to code awareness of it into application objects.
    現在讓我們來看一段業務對象的java 代碼的例子.注意下面沒有Spring的依賴。不像EJB容器,Spring BeanFactory不用嵌入:在應用對象里面你通常不需要編碼.
    代碼:
    public class ExampleBusinessObject implements MyBusinessObject {

    private ExampleDataAccessObject dao;
    private int exampleParam;

    public void setDataAccessObject(ExampleDataAccessObject dao) {
    this.dao = dao;
    }

    public void setExampleParam(int exampleParam) {
    this.exampleParam = exampleParam;
    }

    public void myBusinessMethod() {
    // do stuff using dao
    }
    }


    Note the property setters, which correspond to the XML references in the bean definition document. These are invoked by Spring before the object is used.
    注意屬性設置,在bean定義文檔里面對應XML定義.這將在對象使用之前被Spring調用.

    Such application beans do not need to depend on Spring: They don\\\\\\\'t need to implement any Spring interfaces or extend Spring classes: they just need to observe JavaBeans naming convention. Reusing one outside of a Spring application context is easy, for example in a test environment. Just instantiate it with its default constructor, and set its properties manually, via setDataSource() and setExampleParam() calls. So long as you have a no-args constructor, you are free to define other constructors taking multiple properties if you want to support programmatic construction in a single line of code.
    這種應用bean不需要依靠Spring.他們不需要執行任何Spring接口或者繼承Spring classes:他們只需要遵守JavaBeans名稱轉換.在Spring 應用內容之外重用非常簡單,例如一個測試環境.不過示例定義了一個缺省的構造器,并且通過setDataSource()和setExampleParam()調用配置了屬性。只要你有一個沒有參數的構造器,如果你想在單行代碼支持程序的構件器,你可以自由定義其他的構建器設置其他的屬性.

    Note that the JavaBean properties are not declared on the business interface callers will work with. They are an implementation detail. We could \\\\\\\"plug in\\\\\\\" different implementing classes that have different bean properties without affecting connected objects or calling code.
    注意,在業務借口沒有聲明的JavaBean屬性一起工作. 他們是一個詳細地執行.我們可以插入不同的bean屬性執行classes,而不硬性連接對象或者調用代碼.

    Of course Spring XML bean factories have many more capabilities than described here, but this should give you a feel for the basic approach. As well as simple properties, and properties for which you have a JavaBeans PropertyEditor, Spring can automatically handle lists, maps and java.util.Properties.
    當然,Spring XML bean factories 有更多的能力沒有在這里描述,但是,這將給你在基礎步驟上一個基本的認識.還有簡單屬性,和用于javabean屬性編輯器的屬性,Spring可以自動操作lists,maps和java.util.Properties.
    Bean factories and application contexts are usually associated with a scope defined by the J2EE server, such as:
    Bean factories 和application contexts 通常通過被J2EE server定義一個范圍,例如:

    *The Servlet context. In the Spring MVC framework, an application context is defined for each web application containing common objects. Spring provides the ability to instantiate such a context through a listener or servlet without dependence on the Spring MVC framework, so it can also be used in Struts, WebWork or other web frameworks.
    Servlet context. 在spring MVC 框架里, 一個應用context 可以為每一個飽含基礎對象的web 應用 定義.Spring提供了如示例一樣一個context通過監聽器或者servlet不需要依靠Spring MVC 框架的能力,所以它也可以用于Struts,WebWork 或者其他的web框架.


    *A Servlet: Each controller servlet in the Spring MVC framework has its own application context, derived from the root (application-wide) application context. It also easy to accomplish this with Struts or another MVC framework.
    A Servlet:在Spring MVC 框架里每一個servlet控制器由它特有的應用context,根源于應用context.這同樣可以簡單應用于Struts或者其他的MVC框架.


    *EJB: Spring provides convenience superclasses for EJB that simplify EJB authoring and provide a BeanFactory loaded from an XML document in the EJB Jar file.
    EJB:Spring 提供為EJB創建者方便的超類和在EJB jar 文件里從XML 文檔提供的BeanFactory載入.


    These hooks provided by the J2EE specification generally avoid the need to use a Singleton to bootstrap a bean factory.
    這樣符合J2EE規范通常避免使用Singleton 到 bean factory.
    However, it\\\\\\\'s trivial to instantiate a BeanFactory programmatically if we wish. For example, we could create the bean factory and get a reference to the business object defined above in the following three lines of code:
    不管怎樣,我們將詳細示例一個BeanFactory,下面3行代碼,我們創建一個bean factory 并且作為定義業務對象的參考。

    代碼:
    InputStream is = getClass().getResourceAsStream(\\\\\\\"myFile.xml\\\\\\\");
    XmlBeanFactory bf = new XmlBeanFactory(is);
    MyBusinessObject mbo = (MyBusinessObject) bf.getBean(\\\\\\\"exampleBusinessObject\\\\\\\");


    This code will work outside an application server: it doesn\\\\\\\'s even depend on J2EE, as the Spring IoC container is pure Java.
    這段代碼工作在一個應用server之外:甚至不依靠J2EE,因為Spring IoC容器是純java的.

    JDBC abstraction and data access exception hierarchy
    JDBC 抽象和數據存儲異常層次

    Data access is another area in which Spring shines.
    數據存儲是Spring 的另一個閃光點.

    JDBC offers fairly good abstraction from the underlying database, but is a painful API to use. Some of the problems include:
    JDBC 提供還算不錯的數據庫抽象,但是需要用痛苦的API. 這些問題包含:

     


    The need for verbose error handling to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. This means that correct use of JDBC can quickly result in a lot of code. It’s also a common source of errors. Connection leaks can quickly bring applications down under load.
    麻煩的是需要在用完ResultSets,Statements 和(最重要的)Connections必須關閉. 這意味著正確的使用JDBC得到結果需要一大堆的代碼. 同樣是一個錯誤的根源。Connection泄漏可以馬上讓應用down掉.

    The relatively uninformative SQLException. JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors. Finding out what actually went wrong - for example, was the problem a deadlock or invalid SQL? - involves examining the SQLState and error code. The meaning of these values varies between databases.
    沒有相關的SQLException. JDBC 不能提供異常層次,而是在響應里拋出SQLException.找不出實際是錯誤 – 例如,程序死鎖或者錯誤的SQL? - 包括可檢查的SQLState 和錯誤碼.這可能在數據庫之間出錯.

     

    Spring addresses these problems in two ways:
    Spring 解決這些問題有兩個方法:

     


    By providing APIs that move tedious and error-prone exception handling out of application code into the framework. The framework takes care of all exception handling; application code can concentrate on issuing the appropriate SQL and extracting results.
    通過提供APIs 使 不易移植和錯誤傾向的異常排除在應用代碼之外而到框架層面.這個框架可以照顧到所有的異常操作;應用代碼可以集中發布的適當的SQL和提取結果.


    By providing a meaningful exception hierarchy for your application code to work with in place of SQLException. When Spring first obtains a connection from a DataSource it examines the metadata to ascertain the database. It uses this knowledge to map SQLExceptions to the correct exception in its own hierarchy descended from org.springframework.dao.DataAccessException. Thus your code can work with meaningful exceptions, and need not worry about proprietary SQLState or error codes. Spring’s data access exceptions are not JDBC-specific, so your DAOs are not necessarily tied to JDBC because of the exceptions they may throw.
    為你的應用代碼通過提供一組對SQLException起作用的異常級別.當Spring 第一次在DataSource獲得一個連接,它將核對數據庫的元數據. 在自己的層面利用繪制SQLException 到當前的異常org.springframework.dao.DataAccessException.因而,你的代碼可以和有意義的exceptions一起運行,并且, 不用擔心任何SQLState 或錯誤碼.Spring 的數據存儲異常不是JDBC規范,所以你的DAOs不必依賴JDBC,因為他們可以拋出異常.

     

    Spring provides two levels of JDBC API. The first, in the org.springframework.jdbc.core package, uses callbacks to move control - and hence error handling and connection acquisition and release - from application code inside the framework. This is a different type of Inversion of Control, but equally valuable to that used for configuration management.
    Spring 提供了2個JDBC API的級別. 第一個,在org.springframework.jdbc.core package里面,用callbacks來移動控制- 因此錯誤操作和連接獲得釋放 – 從framework里的應用代碼.這是一種倒置控制的一種不同類型, 然而,這和用配置管理一樣有價值.

    Spring uses a similar callback approach to address several other APIs that involve special steps to acquire and cleanup resources, such as JDO (acquiring and relinquishing a PersistenceManager), transaction management (using JTA) and JNDI. Spring classes that perform such callbacks are called templates.
    Spring 用一個類似的回調方法通過幾個其他的APIs ,這包括特特殊的步驟獲得和清除資源,例如,JDO(獲得和釋放一個PersistenceManager),事務管理(用JTA)和JNDI.Spring classes提供了幾個callbacks 調用模式.

    For example, the Spring JdbcTemplate object can be used to perform a SQL query and save the results in a list as follows:
    例如,Spring JdbcTemplate對象可以用于提供一個SQL query 和保存list結果:

    代碼:

    JdbcTemplate template = new JdbcTemplate(dataSource);
    final List names = new LinkedList();
    template.query(\\\\\\\"SELECT USER.NAME FROM USER\\\\\\\",
    new RowCallbackHandler() {
    public void processRow(ResultSet rs) throws SQLException {
    names.add(rs.getString(1));
    }
    });

     

    Note that application code within the callback is free to throw SQLException: Spring will catch any exceptions and rethrow them in its own hierarchy. The application developer can choose which exceptions, if any, to catch and handle.
    注意這段沒有callback的代碼可以自由的拋出SQLException:Spring 將catch 任何一場和拋出他們自己的異常.應用開發者可以選擇是否將異常捕獲或者處理掉.

    The JdbcTemplate provides many methods to support different scenarios including prepared statements and batch updates. The Spring JDBC abstraction has a very low performance overhead beyond standard JDBC, even in applications cases involving huge result sets.
    JdbcTemplate 提供了許多的方法支持不同的情況, 包括準備statement 和批量更新. Spring JDBC 抽象的性能遠遠超過甚至在應用里包含大量的result sets 標準的JDBC.

    The higher level JDBC abstraction is in the org.springframework.jdbc.object package. This is built on the core JDBC callback functionality, but provides an API in which an RDBMS operation - whether query, update or stored procedure - is modelled as a Java object. This API was partly inspired by the JDO query API, which I found intuitive and highly usable.
    這個較高級的JDBC抽象在org.springframework.jdbc.object 包. 這建立在核心功能JDBC callback上,然而,提供了一組RDBMS操作的APIs – 無論query, update 或者 存儲程序 – 模擬一個java object. 這組API的部分靈感來自JDO query API, 它非常的直觀和有用.

    A query object to return User objects might look like this:
    一個query 對象返回User對象,大概這樣:

    代碼:

    class UserQuery extends MappingSqlQuery {

    public UserQuery(DataSource datasource) {
    super(datasource, \\\\\\\"SELECT * FROM PUB_USER_ADDRESS WHERE USER_ID = ?\\\\\\\");
    declareParameter(new SqlParameter(Types.NUMERIC));
    compile();
    }

    // Map a result set row to a Java object
    protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
    User user = new User();
    user.setId(rs.getLong(\\\\\\\"USER_ID\\\\\\\"));
    user.setForename(rs.getString(\\\\\\\"FORENAME\\\\\\\"));
    return user;
    }

    public User findUser(long id) {
    // Use superclass convenience method to provide strong typing
    return (User) findObject(id);
    }
    }

    This class can be used as follows(這個class按照下列使用):

    代碼:

    User user = userQuery.findUser(25);

    Such objects are often inner classes inside DAOs. They are threadsafe, unless the subclass does something unusual.
    這種對象經常在DAOs用到內部類. 他們線程安全的,除非子類做了不尋常的事情.

    Another important class in the org.springframework.jdbc.object package is the StoredProcedure class. Spring enables a stored procedure to be proxied by a Java class with a single business method. If you like, you can define an interface that the stored procedure implements, meaning that you can free your application code from depending on the use of a stored procedure at all.
    在org.springframework.jdbc.object里面另一些重要的class是StoredProcedure class. Spring 使一個存儲程序能夠被一個具有單個業務方法的Java class代理. 如果你喜歡, 你可以定義一個存儲程序執行的接口, 意思是你可以依靠一個存儲程序的是用來釋放你的應用代碼.


    The Spring data access exception hierarchy is based on unchecked (runtime) exceptions. Having worked with Spring on several projects I’m more and more convinced that this was the right decision.
    Spring 數據存儲異常在運行時不檢查的.對于Spring幾個對象的所有工作, 我認為重中之重是確認這是對的結果.

    Data access exceptions not usually recoverable. For example, if we can’t connect to the database, a particular business object is unlikely to be able to work around the problem. One potential exception is optimistic locking violations, but not all applications use optimistic locking. It’s usually bad to be forced to write code to catch fatal exceptions that can’t be sensibly handled. Letting them propagate to top-level handlers like the servlet or EJB container is usually more appropriate. All Spring data access exceptions are subclasses of DataAccessException, so if we do choose to catch all Spring data access exceptions, we can easily do so.
    數據存儲異常通常不能重新覆蓋. 例如, 如果我們沒有連接數據庫, 一個特殊的業務對象不大可能正常的工作. 潛在的異常是一個樂觀鎖定違例, 但是不是所有的應用都用樂觀鎖定. 這通常分層強制編寫代碼catch 致命的且不能明顯被操作的異常. 像servlet 或者 EJB容器一樣讓他們傳到最上層比較的合適. 所有Spring 數據存儲異常都是DataAccessException的子類,所以如果我們選擇catch所有的數據存儲異常,我們可以簡單的完成.

    Note that if we do want to recover from an unchecked data access exception, we can still do so. We can write code to handle only the recoverable condition. For example, if we consider that only an optimistic locking violation is recoverable, we can write code in a Spring DAO as follows:
    注意如果我們想從一個未檢查的數據訪問異常恢復,我們同樣可以. 我們只有編寫代碼來操作可恢復的條件.例如, 如果我們考慮只有一個樂觀的鎖定是不能恢復的,我們可以在Spring DAO里編寫下列代碼:

    代碼:

    try {
    // do work
    }
    catch (OptimisticLockingFailureException ex) {
    // I\\\\\\\'m interested in this
    }

     

    If Spring data access exceptions were checked, we’d need to write the following code. Note that we could choose to write this anyway:
    如果Spring 數據訪問異常被檢查, 我們需要寫下列代碼. 注意我們可以選擇這么寫:

    代碼:

    try {
    // do work
    }
    catch (OptimisticLockingFailureException ex) {
    // I\\\\\\\'m interested in this
    }
    catch (DataAccessException ex) {
    // Fatal; just rethrow it
    }

     

    One potential objection to the first example - that the compiler can’t enforce handling the potentially recoverable exception - applies also to the second. Because we’re forced to catch the base exception (DataAccessException), the compiler won’t enforce a check for a subclass (OptimisticLockingFailureException). So the compiler would force us to write code to handle an unrecoverable problem, but provide no help in forcing us to deal with the recoverable problem.
    在第一個例子里有一個潛在的缺陷 – 編譯器不能強制操作潛在的不能恢復的異常 – 第二個也是一樣. 因為我們強制catch 基本異常(DataAccessException), 編譯器不能強制為子類(OptimisticLockingFailureException)做檢查.所以編譯器強制我們寫代碼來操作不能恢復的程序,但并不提供任何幫助.

    Spring’s use of unchecked data access exceptions is consistent with that of many - probably most - successful persistence frameworks. (Indeed, it was partly inspired by JDO.) JDBC is one of the few data access APIs to use checked exceptions. TopLink and JDO, for example, use unchecked exceptions exclusively. Gavin King now believes that Hibernate should also have opted for unchecked exceptions.
    Spring 非檢查訪問異常的用法對于大部分情況都是一致的 – 成功的持久框架.(確實,這部分來自JDO的靈感.) JDBC 是一個在少數用于check exception數據訪問的APIs.TopLink 和JDO,例如,不特定檢查異常. Gavin King 現在艱辛Hibernate 也不檢查unchecked exception.

    Spring JDBC can help you in several ways:
    Spring JDBC 可以幫助一下列幾點:

    You’ll never need to write a finally block again to use JDBC
    根本不必像用JDBC一樣寫finally.

    You’ll need to write much less code overall
    不必寫大量大代碼


    You’ll never need to dig through your RDBMS documentation to work out what obscure error code it returns for a bad column name. Your application won’t be dependent on RDBMS-specific error handling code.
    不必鉆研關系數據庫文檔就可以解決為一個錯誤列名而返回的隱含錯誤碼.你的應用還不用依靠關系數據庫制定的錯誤操作碼.


    Whatever persistence technology use, you’ll find it easy to implement the DAO pattern without business logic depending on any particular data access API.
    不管怎樣持久技術的使用,可以使你方便的實現DAO模式,而業務邏輯不依靠任何特殊的數據訪問API.


    In practice we find that all this amounts to substantial productivity gains and fewer bugs. I used to loathe writing JDBC code; now I find that I can focus on the SQL I want to execute, rather than the incidentals of JDBC resource management.
    在實踐中我們可以找到完全的實質生產力數量和更少的bugs. 我們憎恨JDBC代碼;現在我可以把精力放在我想執行的SQL上,總比附加JDBC的資源管理要好得多.

    Spring’s JDBC abstraction can be used standalone if desired - you are not forced to use the other parts of Spring.
    Spring的JDBC 抽象可以單獨使用 – 一個可以只用Spring的其他部分.

    posted on 2005-02-04 11:17 jacky 閱讀(510) 評論(0)  編輯  收藏 所屬分類: Open source
    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    常用鏈接

    留言簿(10)

    隨筆檔案

    文章分類

    文章檔案

    相冊

    收藏夾

    java

    搜索

    •  

    最新評論


    主站蜘蛛池模板: 国产免费一区二区三区不卡| 精选影视免费在线 | 免费在线视频你懂的| 亚洲国产成人久久综合一| 最近中文字幕大全免费版在线 | 性生交片免费无码看人| 亚洲国产精品成人精品软件| 8090在线观看免费观看| 亚洲精彩视频在线观看| 无码国产精品一区二区免费虚拟VR| 亚洲精品一区二区三区四区乱码| 95老司机免费福利| 亚洲中文字幕AV在天堂| 国产精品极品美女免费观看| 亚洲AV无码AV男人的天堂不卡| 四虎影视在线永久免费观看| 特级毛片在线大全免费播放| 激情97综合亚洲色婷婷五| 久久久久久国产精品免费免费男同 | 亚洲爆乳大丰满无码专区| 国产成人精品男人免费| www成人免费视频| 亚洲av无码一区二区三区不卡| 一级毛片在线观看免费| 亚洲午夜无码久久久久小说| 免费国产精品视频| 高清永久免费观看| 亚洲一区中文字幕在线观看| 午夜网站免费版在线观看| 人体大胆做受免费视频| 亚洲自偷自偷精品| 免费观看的a级毛片的网站| 一级特级aaaa毛片免费观看 | 最新国产乱人伦偷精品免费网站| 亚洲国产精品久久网午夜| 国产成人免费a在线资源| 成人性生交大片免费看中文| 亚洲国产精品久久丫| 哒哒哒免费视频观看在线www | 免费日本一区二区| 亚洲国产日韩精品|