Spring参考文档翻译04--IOC容器02

1.2. Container Overview

容器概述

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 Tools for Eclipse (an Eclipse-powered development environment), you can easily create this boilerplate configuration with a few mouse clicks or keystrokes.

在大多数应用场景中,不需要显式用户来实例化Spring IOC容器的一个或多个容器。例如,在Web应用程序场景中,应用程序web.xml中简单的八行(左右)样板web描述符XML通常就足够了(请参阅方便的web应用程序的ApplicationContext实例化)。如果您使用Spring Tools for Eclipse(一个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创建和初始化之后,您拥有一个完全配置且可执行的系统或应用程序。

Figure 1. The Spring IoC container

图1.SpringIOC容器

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 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容器的关键概念和特性。

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的元数据不是唯一允许的配置元数据形式。SpringIOC容器本身与实际编写此配置元数据的格式完全分离。如今,许多开发人员为其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.

    基于注解的配置:Spring2.5引入了对基于注解的配置元数据的支持。

  • 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.

    基于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配置为<bean/>顶级元素内的<beans/>元素。在@Confiuration类中Java配置通常@Bean-annotated方法。

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容器控制之外创建的对象,请参阅Use AspectJ to dependency-inject domain objects with 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.
该id属性是标识单个bean定义的字符串。
The class attribute defines the type of the bean and uses the fully qualified classname.
该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

实例化一个容器

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。

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
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类和两个数据访问对象组成JpaAccountDao(JpaItemDao基于JPA对象-关系映射标准)。property name 元素引用JavaBean属性的名称,元素ref引用另一个bean定义的名称。id元素之间的这种联系ref表达了协作对象之间的依赖关系。有关配置对象依赖项的详细信息,请参阅依赖项。

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 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. 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.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. 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.xml,messageSource.xml和themeSource.xml。所有位置路径都相对于执行导入的定义文件,因此service.xml必须与执行导入的文件位于同一目录或类路径位置,而messageSource.xml并且themeSource.xml必须位于resources导入文件位置下方的位置。如您缩减,前导斜杠被忽略。但是,鉴于这些路径是相对的,最好不要使用斜线。根据Spring Schema,被导入文件的内容,包括顶级<beans/>元素,必须是有效的XMLbean定义。

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.xml或classpath:/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.

命名空间本身提供了导入指令功能,除了普通的bean定义之外更多的配置特性可以在Spring提供的XML命名空间的选择中使用---例如:the context和util命名空间。

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配置命名空间。它还允许通过import Beans指令导入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. By using the method T getBean(String name, Class<T> requiredType), you can retrieve instances of your beans.

ApplicationContext是一个高级工厂的接口,能够维护不同bean及其依赖项的注册表。通过使用method T getBean(String name,Class<T> requiredType),您可以检索bean的实例。

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

允许您读取bean定义并访问它们,如以下ApplicationContext示例所示:

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

With Groovy configuration, bootstrapping looks very similar. It has a different context implementation class which is Groovy-aware (but also understands XML bean definitions). The following example shows Groovy configuration:

使用Groovy配置,引导看起来非常相似。它有一个不同的上下文实现类,它支持Groovy(但也理解XML bean定义)。以下示例显示了Groovy配置:

ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");

The most flexible variant is GenericApplicationContext in combination with reader delegates — for example, with XmlBeanDefinitionReader for XML files, as the following example shows:

最灵活的变体是GenericApplicationContext与阅读器委托结合使用--例如,与XmlBeanDefinitionReader XML文件结合使用,如以下示例所示:

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

You can also use the GroovyBeanDefinitionReader for Groovy files, as the following example shows:

你也可以使用GroovyBeanDefintionReader的Groovy 文件,正如下面的案例所示:

GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
context.refresh();

You can mix and match such reader delegates on the same ApplicationContext, reading bean definitions from diverse configuration sources.

你可以在同一个上混合和匹配此类阅读器委托ApplicationContext,从不同的配置元读取bean定义。

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 have 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, letting you declare a dependency on a specific bean through metadata (such as an autowiring annotation).

然后,您可以使用它getBean来检索bean的实例。该ApplicationContext接口还有一些其他检索bean的方法,但是理想情况下,您的应用程序代码不应该使用它们。实际上,您的应用程序代码不应该调用该getBean()方法,因此根本不依赖Spring API。例如,Spring与Web框架的集成为各种Web框架组件(例如控制器与JSF管理的bean)提供了依赖注入,让您可以通过元数据(例如自动装配注释)声明对特定bean的依赖。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值