1.2 容器概述

官方英文版地址:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html

备注:翻译如有不对,请多指正,谢谢。

1.2. Container overview

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned 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 allows you to express the objects that compose your application and the rich interdependencies between such objects.

org.springframework.context.ApplicationContext接口代表了Spring IoC容器,并且负责Bean的实例化、配置和Bean之间的一来装配。容器通过读取配置元数据来获取关于对象实例化、配置和装配的相关信息。配置元数据可以用XML文件、Java注解和Java代码的方式呈现。它允许你去表达组成你应用程序的对象以及这些对象之间的复杂关系。

Several implementations of the ApplicationContext interface are supplied out-of-the-box with Spring. In standalone 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早已成为定义配置元数据的传统形式,但你仍然可以使用java注解或者代码方式提供少量XML配置来支持哪些额外的元数据配置。

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 will typically suffice (see Convenient ApplicationContext instantiation for web applications). If you are using the Spring Tool Suite Eclipse-powered development environment this boilerplate configuration can be easily created with few mouse clicks or keystrokes.

在大多数应用程序场景中,用户不需要显示的代码来初始化一个或多个Spring IoC容器中的实例。举个例子,在Web应用程序场景中,一个简单的8行web.xml描述符配置通常就足够了(参见 Convenient ApplicationContext instantiation for web applications)。如果你正在使用基于Eclipse的Spring开发套件开发,这些样板配置只需要简单的几次鼠标点击或者敲击键盘就可以轻松创建。

The following diagram is 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之后,你的应用程序类和配置元数据相结合,你就有了一个完整配置的可执行系统或应用程序。

container magic

图1:Spring IoC容器

1.2.1. Configuration metadata

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容器使用一组配置元数据,这些配置元数据代表了作为应用开发者的你告诉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容器概念和特性。

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容器本身与配置元数据的方式完全分离。现在,许多开发人员为他们的Spring应用程序选择基于Java的配置。

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

  • 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容器配置元数据的方式,可以参见:

  • 基于注解的配置:从Spring2.5开始,引入了基于注解的配置元数据。
  • 基于Java的配置:从Spring3.0开始,许多由Spring JavaConfig项目提供的特性称为了Spring核心框架的一部分。因此,你可以使用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 shows these beans configured as <bean/> elements inside a top-level <beans/> element. Java configuration typically uses @Bean annotated methods within a @Configuration class.

Spring配置包含至少一个由容器管理的Bean定义,通常不只一个。基于XML的配置元数据,通常使用<bean/>来定义一个Bean,而<bean/>节点位于<beans/>顶层节点下。基于Java的配置通常使用在@Configuraion注解的类中的@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定义对应于组成你应用程序的实际对象。通常我们定义服务层对象、数据访问层对象(DAOs)、展现层对象(如Struts的Action实例)、基础设施对象(如Hibernate SessionFactories、JMS队列等等)。通常,在容器中,不会配置细粒度的领域对象,因为创建和加载域对象通常是DAOs和业务逻辑的职责。你可以使用Spring和AspectJ的集成来配置在IoC容器之外创建的对象。可以参阅 Using AspectJ to dependency-inject domain objects with Spring

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

The id attribute is a string that you use to identify the individual bean definition. The class attribute defines the type of the bean and uses the fully qualified classname. 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.

下面的例子展示了基于XML格式配置元数据的基本格式:

id属性是用于标识每个Bean定义的字符串。class属性定义了Bean的类型并且使用类的完全限定名。id的属性值用来引用对象。本例中在XML中没有显示引用协作对象。想要了解更多信息,可以参阅Dependencies

<?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="..." 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>

1.2.2. Instantiating a container

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

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

实例化SpringIoC容器很简单。提供给ApplicationContext构造函数的定位路径实际上是用来提供给容器加载配置元数据的资源字符串。这些资源包括本地文件系统、Java类加载路径等等。

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资源抽象的知识,如Resources介绍所示,它提供了一种方便的从URI语法描述的位置读取流的机制。特别地,资源路径通常被用来构造应用上下文,如 Application contexts and Resource paths介绍的所示。

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

接下来的例子展示了服务层对象的配置元数据定义:

<?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">

    <!-- 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:

而接下来的这个例子,则展示了数据访问层的对象定义配置元数据:

<?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="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 class PetStoreServiceImpl, and two data access objects of the type 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类和两个数据访问层对象(分别为JpaAccountDao和JpaItemDao)。properties元素的name属性代表了Bean的名称,ref元素引用另一个Bean的名称。id和ref之间的链接关系表达了协作对象之间的依赖关系。想要了解配置对象依赖的更多信息,可以参阅 Dependencies

Composing XML-based configuration metadata

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.

You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, 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. For example:

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

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

通过多个XML文件来进行Bean定义通常较为有用。通常,每个独立的XML配置文件代表一个你应用程序中的逻辑层或者模块。你可以使用应用程序上下文构造函数来从这些XML片段中加载Bean定义。如前面章节所示,构造函数接受对个资源定位符。或者使用一个或多个<import/>元素来从其他文件加载Bean定义。

In the preceding example, external bean definitions are loaded from three files: services.xml, messageSource.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, but 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.xml、messageSource.xml和themeSource.xml。所有的位置路径都是相对于执行导入操作的定义文件的。因此,services.xml必须和执行导入的定义文件处于同一个目录或者类路径,而messageSource.xml和themeSource.xml必须在定义文件同级目录resources下面。如您缩减,前导斜杠被忽略了,也鉴于此,这些路径是相对的。最好不要使用斜杠。被导入文件的内容,包含顶层元素<beans/>,必须是有效的Spring XML定位格式。

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.

可以使用“../”路径来引用上一层目录中的文件,但是并不推荐这么做。这样做,会对当前应用程序之外的文件创建依赖。特别底,对于以classpath开头的路径更不推荐使用这种方式来访问上级目录文件,如“classpath:../services.xml”。在运行时,会选在最近的classpath根目录并查找它的父目录。类路径配置的改变将可能导致不同的不正确的上层目录。

The import directive is a feature provided by the beans namespace itself. Further configuration features beyond plain bean definitions are available in a selection of XML namespaces provided by Spring, e.g. the "context" and the "util" namespace.

import命令是bean命令空间自己提供的特性。在Spring提供的XML命名空间中,除了普通的bean定义之外,还可以使用其他配置特性。

1.2.3. Using the container

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

The ApplicationContext enables you to read bean definitions and access them as follows:

ApplicationContext是一个高级工厂接口,能够维护不同的对象注册表及其之间的依赖关系。使用getBean(String name, Class<T> requiredType)方法你可以获取到你定义的Bean对象。

你可以使用ApplicationContext来读取Bean定义,并且获取它们,如下所示:

// 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();

The most flexible variant is GenericApplicationContext in combination with reader delegates, e.g. with XmlBeanDefinitionReader for XML files:

最灵活的变体是GenericApplicationContext和reader delegate的结合,使用XmlBeanDefinitionReader来读取XML文件:

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();

You can then use getBean to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all. For example, Spring’s integration with web frameworks provides dependency injection for various web framework components such as controllers and JSF-managed beans, allowing you to declare a dependency on a specific bean through metadata (e.g. an autowiring annotation).

你可以使用getBean方法来获取你所定义的Bean对象。ApplicationContext接口有一些其他的获取bean对象的方法,但是理想情况下你不会使用到它们。实际上,应用程序代码不应该调用getBean方法,根本不应该依赖于Spring API。举个例子,Spring与Web框架的集成,为各种Web框架组件提供了依赖注入,允许你使用元数据定义来声明对特定Bean的依赖。

猜你喜欢

转载自blog.csdn.net/andamajing/article/details/81604666
1.2
今日推荐