Spring Framework官方文檔翻譯(中英文版)


Version 5.2.0.RELEASE

5.2.0版本

 

Core Technologies

 

一、核心技術

     This part of the reference documentation covers all the technologies that are absolutely integral to the Spring Framework.

       參考文檔的這一部分涵蓋了Spring框架必不可少的所有技術。

       Foremost amongst these is the Spring Framework’s Inversion of Control (IoC) container. A thorough treatment of the Spring Framework’s IoC container is closely followed by comprehensive coverage of Spring’s Aspect-Oriented Programming (AOP) technologies. The Spring Framework has its own AOP framework, which is conceptually easy to understand and which successfully addresses the 80% sweet spot of AOP requirements in Java enterprise programming.

       其中最重要的是Spring框架的控制反轉(IoC)容器。對Spring框架的IoC容器進行徹底處理之后,將全面介紹Spring的面向方面編程(AOP)技術。Spring框架擁有自己的AOP框架,該框架在概念上易於理解,並且成功解決了Java企業編程中AOP要求的80%的難題。

       Coverage of Spring’s integration with AspectJ (currently the richest — in terms of features — and certainly most mature AOP implementation in the Java enterprise space) is also provided.

       還提供了Spring與AspectJ的集成(就功能而言,目前是最豐富的-當然肯定是Java企業領域中最成熟的AOP實現)。

1. The IoC Container

 

1. IoC容器

      This chapter covers Spring’s Inversion of Control (IoC) container.

      本章介紹了Spring的控制反轉(IoC)容器。

 

1.1. Introduction to the Spring IoC Container and Beans

 

1.1. Spring IoC容器和Bean簡介

       This chapter covers the Spring Framework implementation of the Inversion of Control (IoC) principle. IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes or a mechanism such as the Service Locator pattern.

       本章介紹了控制反轉(IoC)原理的Spring框架實現。IoC也稱為依賴注入(DI)。在此過程中,對象僅通過構造函數參數,工廠方法的參數或在構造或從工廠方法返回后在對象實例上設置的屬性來定義其依賴項(即,與它們一起使用的其他對象) 。然后,容器在創建bean時注入那些依賴項。此過程從根本上講是通過使用類的直接構造或諸如服務定位器模式之類的方法來控制其依賴項的實例化或位置的bean本身的逆過程(因此稱為Control Inversion)。    

      The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. ApplicationContext is a sub-interface of BeanFactory. It adds:

 

       org.springframework.beansorg.springframework.context包是Spring框架的IoC容器的基礎。BeanFactory接口提供了一種高級配置機制,能夠管理任何類型的對象。 ApplicationContext是BeanFactory的子接口它增加了

 

  • Easier integration with Spring’s AOP features

  • Message resource handling (for use in internationalization)

  • Event publication

  • Application-layer specific contexts such as the WebApplicationContext for use in web applications.

 

  • 更容易與Spring的AOP特性集成

  • 消息資源處理(用於國際化)

  • 事件發布

  • 特定於應用程序層的上下文,如用於web應用程序的WebApplicationContext。

       In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality. The ApplicationContext is a complete superset of the BeanFactory and is used exclusively in this chapter in descriptions of Spring’s IoC container. For more information on using the BeanFactory instead of the ApplicationContext, see The BeanFactory.

       簡而言之,BeanFactory提供了配置框架和基本功能,並且ApplicationContext增加了更多針對企業的功能。ApplicationContext是BeanFactory的一個完整超集,在本章描述Spring的IoC容器時專門使用它。有關使用BeanFactory而不是ApplicationContext的更多信息,請參見BeanFactory相關文檔。

       In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.       

       在Spring中,構成應用程序主干並由Spring IoC容器管理的對象稱為bean。Bean是由Spring IoC容器實例化,組裝和以其他方式管理的對象。否則,bean僅僅是應用程序中許多對象之一。Bean及其之間的依賴關系反映在容器使用的配置元數據中。

1.2. Container Overview

1.2. 容器概述

       The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It lets you express the objects that compose your application and the rich interdependencies between those objects.

        org.springframework.context.ApplicationContext接口代表Spring IoC容器,並負責實例化,配置和組裝Bean。容器通過讀取配置元數據來獲取有關要實例化,配置和組裝哪些對象的指令。配置元數據以XML,Java注解或Java代碼表示。它允許您表達組成應用程序的對象以及這些對象之間豐富的相互依賴關系。

        Several implementations of the ApplicationContext interface are supplied with Spring. In stand-alone applications, it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has been the traditional format for defining configuration metadata, you can instruct the container to use Java annotations or code as the metadata format by providing a small amount of XML configuration to declaratively enable support for these additional metadata formats.

        Spring提供了ApplicationContext接口的幾種實現方式。在獨立應用程序中,通常創建ClassPathXmlApplicationContext或FileSystemXmlApplicationContext的實例。盡管XML是定義配置元數據的傳統格式,但是您可以通過提供少量XML配置來聲明性地啟用對這些其他元數據格式的支持,從而指示容器將Java注解或代碼用作元數據格式。

        In most application scenarios, explicit user code is not required to instantiate one or more instances of a Spring IoC container. For example, in a web application scenario, a simple eight (or so) lines of boilerplate web descriptor XML in the web.xml file of the application typically suffices (see Convenient ApplicationContext Instantiation for Web Applications). If you use the Spring Tool Suite (an Eclipse-powered development environment), you can easily create this boilerplate configuration with a few mouse clicks or keystrokes.

        在大多數應用程序場景中,不需要顯式的用戶代碼來實例化一個或多個Spring IoC容器實例。例如,在Web應用程序場景中,應用程序文件中在web.xml中寫上8行左右的代碼通常就足夠了(請參閱Web應用程序的便捷ApplicationContext實例化)。如果使用 Spring Tool Suite(基於Eclipse的開發環境),則只需單擊幾次鼠標或擊鍵即可輕松創建此樣板配置。

        The following diagram shows a high-level view of how Spring works. Your application classes are combined with configuration metadata so that, after the ApplicationContext is created and initialized, you have a fully configured and executable system or application.

        下圖顯示了Spring的工作原理的高級視圖。您的應用程序類與配置元數據結合在一起,因此,在ApplicationContext創建和初始化后,您將擁有一個完全配置且可執行的系統或應用程序。

                                                                                        

 

                                                                                                                        圖1. Spring IoC容器

1.2.1. Configuration Metadata

 1.2.1. 配置元數據

        As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata. This configuration metadata represents how you, as an application developer, tell the Spring container to instantiate, configure, and assemble the objects in your application.

        如上圖所示,Spring IoC容器使用一種配置元數據形式。這個配置元數據表示您作為應用程序開發人員如何告訴Spring容器在應用程序中實例化,配置和組裝對象。

        Configuration metadata is traditionally supplied in a simple and intuitive XML format, which is what most of this chapter uses to convey key concepts and features of the Spring IoC container.

        傳統上,配置元數據以簡單直觀的XML格式提供,這是本章大部分內容用來傳達Spring IoC容器的關鍵概念和功能的內容。

        note: XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written. These days, many developers choose Java-based configuration for their Spring applications.

        注:基於XML的元數據不是配置元數據的唯一允許形式。Spring IoC容器本身與實際寫入此配置元數據的格式完全脫鈎。如今,許多開發人員為他們的Spring應用程序選擇 基於Java的配置。

        For information about using other forms of metadata with the Spring container, see:

        有關在Spring容器中使用其他形式的元數據的信息,請參見:

  • Annotation-based configuration: Spring 2.5 introduced support for annotation-based configuration metadata.

  • Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework. Thus, you can define beans external to your application classes by using Java rather than XML files. To use these new features, see the @Configuration, @Bean, @Import, and @DependsOn annotations.

  • 基於注解的配置:Spring 2.5引入了對基於注解的配置元數據的支持。

  • 基於Java的配置:從Spring 3.0開始,Spring JavaConfig項目提供的許多功能成為核心Spring Framework的一部分。因此,您可以使用Java而不是XML文件來定義應用程序類外部的bean。要使用這些新功能,請參閱 @Configuration, @Bean, @Import,和@DependsOn注解。

       Spring configuration consists of at least one and typically more than one bean definition that the container must manage. XML-based configuration metadata configures these beans as <bean/> elements inside a top-level <beans/> element. Java configuration typically uses @Bean-annotated methods within a @Configuration class.

       Spring配置由容器必須管理的至少一個(通常是一個以上)bean定義組成。基於xml的配置元數據將這些bean配置為頂級<beans/>元素中的<bean/>元素。Java配置通常在@Configuration注解的類中使用@bean注解的方法。

       These bean definitions correspond to the actual objects that make up your application. Typically, you define service layer objects, data access objects (DAOs), presentation objects such as Struts Action instances, infrastructure objects such as Hibernate SessionFactories, JMS Queues, and so forth. Typically, one does not configure fine-grained domain objects in the container, because it is usually the responsibility of DAOs and business logic to create and load domain objects. However, you can use Spring’s integration with AspectJ to configure objects that have been created outside the control of an IoC container. See Using AspectJ to dependency-inject domain objects with Spring.

       這些bean定義對應於組成應用程序的實際對象。通常,您定義服務層對象,數據訪問對象(DAO),表示對象(例如Struts Action實例),基礎結構對象(例如Hibernate SessionFactories,JMS Queues等)。通常,不會在容器中配置細粒度的域對象,因為創建和加載域對象通常是DAO和業務邏輯的職責。但是,您可以使用Spring與AspectJ的集成來配置在IoC容器的控制范圍之外創建的對象。請參閱使用AspectJ與Spring依賴注入域對象。

        The following example shows the basic structure of XML-based configuration metadata:

        以下示例顯示了基於XML的配置元數據的基本結構:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

   The id attribute is a string that identifies the individual bean definition.

        The class attribute defines the type of the bean and uses the fully qualified classname.

         注:id屬性是標識單個bean定義的字符串。

               class屬性定義Bean的類型,並使用完全限定的類名。

       The value of the id attribute refers to collaborating objects. The XML for referring to collaborating objects is not shown in this example. See Dependencies for more information.

       該id屬性的值是指協作對象。在此示例中未顯示用於引用協作對象的XML。有關更多信息,請參見 依賴項。

1.2.2. Instantiating a Container

1.2.2. 實例化一個容器

       The location path or paths supplied to an ApplicationContext constructor are resource strings that let the container load configuration metadata from a variety of external resources, such as the local file system, the Java CLASSPATH, and so on.

       資源字符串提供給ApplicationContext構造函數的一個或多個位置路徑,這些資源字符串使容器可以從各種外部資源(例如本地文件系統,Java等)加載配置元數據CLASSPATH

       Java: ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

       Kotlin: val context = ClassPathXmlApplicationContext("services.xml", "daos.xml")

       note: After you learn about Spring’s IoC container, you may want to know more about Spring’s Resource abstraction (as described in Resources), which provides a convenient mechanism for reading an InputStream from locations defined in a URI syntax. In particular, Resource paths are used to construct applications contexts, as described in Application Contexts and Resource Paths.

       注:在了解了Spring的IoC容器之后,您可能想了解更多有關Spring的 Resource抽象概念(如參考資料中所述),它提供了一種方便的機制,用於從URI語法中定義的位置讀取InputStream。具體而言,Resource如應用程序上下文和資源路徑中所述, 路徑用於構造應用程序上下文。

       The following example shows the service layer objects (services.xml) configuration file:

       下面的示例顯示了服務層對象(services.xml)配置文件:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- services -->

    <bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for services go here -->

</beans>

  The following example shows the data access objects daos.xml file:

        下面的示例顯示了數據訪問對象daos.xml文件:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao"
        class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions for data access objects go here -->

</beans>

  In the preceding example, the service layer consists of the PetStoreServiceImpl class and two data access objects of the types JpaAccountDao and JpaItemDao (based on the JPA Object-Relational Mapping standard). The property name element refers to the name of the JavaBean property, and the ref element refers to the name of another bean definition. This linkage between id and ref elements expresses the dependency between collaborating objects. For details of configuring an object’s dependencies, see Dependencies.

       在前面的示例中,服務層由的PetStoreServiceImpl類和類型的兩個數據訪問對象JpaAccountDaoJpaItemDao(基於JPA對象關系映射標准)。property name元素是指JavaBean屬性的名稱,以及ref元素指的是另一個bean定義的名稱。idref元素之間的這種聯系表達了協作對象之間的依賴性。有關配置對象的依賴關系的詳細信息,請參見依賴關系。

Composing XML-based Configuration Metadata
組成基於XML的配置元數據

       It can be useful to have bean definitions span multiple XML files. Often, each individual XML configuration file represents a logical layer or module in your architecture.

       使bean定義跨越多個XML文件可能很有用。通常,每個單獨的XML配置文件都代表體系結構中的邏輯層或模塊。

       You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resourcelocations, as was shown in the previous section. Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files. The following example shows how to do so:

        您可以使用應用程序上下文構造函數從所有這些XML片段中加載bean定義。Resource如上一節中所示,此構造函數具有多個位置 或者,使用一個或多個出現的<import/>元素從另一個文件中加載bean定義。以下示例顯示了如何執行此操作:

<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

  In the preceding example, external bean definitions are loaded from three files: services.xmlmessageSource.xml, and themeSource.xml. All location paths are relative to the definition file doing the importing, so services.xml must be in the same directory or classpath location as the file doing the importing, while messageSource.xml and themeSource.xml must be in a resources location below the location of the importing file. As you can see, a leading slash is ignored. However, given that these paths are relative, it is better form not to use the slash at all. The contents of the files being imported, including the top level <beans/> element, must be valid XML bean definitions, according to the Spring Schema.

       在前面的例子中,外部bean定義是從三個文件加載: services.xmlmessageSource.xml,和themeSource.xml。所有位置路徑都相對於執行導入的定義文件,因此,services.xml必須與執行導入的文件位於相同的目錄或類路徑位置messageSource.xml和themeSource.xml必須在resources文件夾下,resources文件夾必須與執行導入的文件位於相同的目錄或類路徑位置。可以看到,前面的斜杠被忽略了。但是,考慮到這些路徑是相對的,所以最好不要使用斜杠。根據Spring模式,要導入的文件的內容,包括頂級的<beans/>元素,必須是有效的XML bean定義。

       note: It is possible, but not recommended, to reference files in parent directories using a relative "../" path. Doing so creates a dependency on a file that is outside the current application. In particular, this reference is not recommended for classpath: URLs (for example, classpath:../services.xml), where the runtime resolution process chooses the “nearest” classpath root and then looks into its parent directory. Classpath configuration changes may lead to the choice of a different, incorrect directory.

       You can always use fully qualified resource locations instead of relative paths: for example, file:C:/config/services.xml or classpath:/config/services.xml. However, be aware that you are coupling your application’s configuration to specific absolute locations. It is generally preferable to keep an indirection for such absolute locations — for example, through "${…​}" placeholders that are resolved against JVM system properties at runtime.

       注:可以但不建議使用相對的“ ../”路徑引用父目錄中的文件。這樣做會創建對當前應用程序外部文件的依賴。特別是,對於運行時解析過程選擇“最近的”類路徑根目錄然后查找其父目錄的classpath:URL(例如classpath:../services.xml,不建議使用此引用。類路徑配置更改可能導致選擇不同的、不正確的目錄。

       您始終可以使用完全限定的資源位置來代替相對路徑:例如file:C:/config/services.xmlclasspath:/config/services.xml。但是,請注意,您正在將應用程序的配置耦合到特定的絕對位置。通常最好為這樣的絕對位置保留一個間接尋址,例如,通過在運行時針對JVM系統屬性解析的“ $ {…}”占位符。

        The namespace itself provides the import directive feature. Further configuration features beyond plain bean definitions are available in a selection of XML namespaces provided by Spring — for example, the context and util namespaces.

         命名空間本身提供了導入指令功能。Spring提供的一系列XML名稱空間(例如contextutil名稱空間)中提供了超出普通bean定義的其他配置功能

The Groovy Bean Definition DSL
Groovy Bean定義DSL

          As a further example for externalized configuration metadata, bean definitions can also be expressed in Spring’s Groovy Bean Definition DSL, as known from the Grails framework. Typically, such configuration live in a ".groovy" file with the structure shown in the following example:

          作為外部化配置元數據的另一個示例,Bean定義也可以在Spring的Groovy Bean定義DSL中表達,這從Grails框架中可以知道。通常,這種配置位於“ .groovy”文件中,其結構如以下示例所示:

 

beans {
    dataSource(BasicDataSource) {
        driverClassName = "org.hsqldb.jdbcDriver"
        url = "jdbc:hsqldb:mem:grailsDB"
        username = "sa"
        password = ""
        settings = [mynew:"setting"]
    }
    sessionFactory(SessionFactory) {
        dataSource = dataSource
    }
    myService(MyService) {
        nestedBean = { AnotherBean bean ->
            dataSource = dataSource
        }
    }
}

 

  This configuration style is largely equivalent to XML bean definitions and even supports Spring’s XML configuration namespaces. It also allows for importing XML bean definition files through an importBeans directive.

        這種配置樣式在很大程度上等同於XML bean定義,甚至支持Spring的XML配置名稱空間。它還允許通過importBeans指令導入XML bean定義文件

1.2.3. Using the Container

1.2.3. 使用容器

        The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. By using the method T getBean(String name, Class<T> requiredType), you can retrieve instances of your beans.

         ApplicationContext是一個維護bean定義以及相互依賴的注冊表的高級工廠的接口。通過使用方法T getBean(String name, Class<T> requiredType),您可以檢索bean的實例。

         The ApplicationContext lets you read bean definitions and access them, as the following example shows:

          ApplicationContext允許您讀取bean定義並訪問它們,如下面的示例所示:

Java:

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

// use configured instance
List<String> userList = service.getUsernameList();

Kotlin: 

import org.springframework.beans.factory.getBean

// create and configure beans
val context = ClassPathXmlApplicationContext("services.xml", "daos.xml")

// retrieve configured instance
val service = context.getBean<PetStoreService>("petStore")

// use configured instance
var userList = service.getUsernameList()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM