SpringFramework翻译_2Core Technologies(核心技术1.2系列)

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容器,并负责实例化、配置和组装beans。容器通过读取配置元数据获得关于实例化、配置和组装对象的指令。配置元数据用XML、Java annotations或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一直是定义配置元数据的传统格式,但您可以使用Java annotations 或代码以及少量的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 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文件的web描述性XML仅需要大概八行就够了(请参阅 Convenient ApplicationContext Instantiation for Web Applications)。如果您使用Spring工具套件(一个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之后,您就有了一个完整配置的可执行系统或应用程序。


SpringFramework翻译_2Core Technologies(核心技术1.2系列)_第1张图片
image

Figure 1. The Spring IoC container

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.
For information about using other forms of metadata with the Spring container, see:

基于xml的元数据不是配置元数据的唯一形式。Spring IoC容器本身与实际编写配置元数据的格式完全分离。现在,许多开发人员为他们的Spring应用程序选择基于java的配置。
有关使用Spring容器的其他元数据形式的信息,请参阅:

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

基于注解的配置:Spring 2.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框架的一部分。这样,才可以通过使用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 elements inside a top-level element. Java configuration typically uses @Bean-annotated methods within a @Configuration class.

Spring配置包含至少一个bean定义,通常是容器必须管理多个bean的定义。基于xml的配置元数据将这些beans以的方式插入在节点内。Java配置通常在@Configuration类中使用@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定义了组成应用程序的实际对象。通常,您可以定义服务层对象、数据访问对象(DAOs)、表示对象(如Struts Action实例)、基础设施对象(如Hibernate SessionFactories)、JMS队列等。通常,在容器中不配置详细的domain对象,因为创建和加载它们通常是DAOs和业务逻辑的责任。但是,您可以使用Spring与AspectJ的集成来配置在IoC容器控制之外创建的对象。请参阅使用AspectJ来依赖带有Spring的注入域对象。

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

下面的例子展示了基于xml的配置元数据的基本结构:




       
        
    

    
        
    

    


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.
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属性是标识单个bean的字符串。

class属性定义了bean的类型并使用classname的完整类名。

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构造函数的资源物理path或paths是允许容器从各种外部资源(如本地文件系统、Java类路径等)加载的字符串。

ApplicationContext context = new 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的资源抽象(如参考资料中所述)的更多内容,它提供了从URI中定义的位置读取InputStream的方便机制。特别是,资源路径用于构造应用程序上下文,正如在应用程序上下文和资源路径中描述的那样。

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

下面的示例显示了服务层对象(service.xml)配置文件:




    

    
        
        
        
    

    


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

下面的示例显示了数据访问对象daos.xml文件:




    
        
    

    
        
    

    


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对象关系映射标准)。属性名称元素引用JavaBean属性的名称,ref元素引用另一个bean定义的名称。id和ref元素之间的链接表示协作对象之间的依赖关系。有关配置对象依赖项的详细信息,请参阅依赖项。

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.

组合基于xml的配置元数据
让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 element to load bean definitions from another file or files. The following example shows how to do so:

您可以使用应用程序上下文构造函数从所有这些XML片段加载bean定义。如前一节所示,此构造函数接受多个资源位置。或者,使用元素来从另一个或多个文件加载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. 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 element, must be valid XML bean definitions, according to the Spring Schema.

在前面的示例中,从三个文件(service.xml,messageSource.xml和themeSource.xml)加载外部bean定义。所有位置路径都在执行导入操作文件的相对位置,因此是service.xml必须与执行导入的文件位于相同的目录或classpath位置,而messageSource.xml和themeSource.xml必须位于导入文件位置下方的资源位置。如您所见,前面的斜杠可以被忽略。但是,考虑到这些路径是相对的,最好不要使用斜杠。根据Spring Schema,导入的文件的内容,包括顶层元素,必须是有效的XML bean定义。

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: URLs(例如,classpath:../services.xml),它会在运行时解析过程选择“最近的”classpath根目录,然后查看它的父目录。类路径配置更改可能导致选择不同的、不正确的目录。

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.

您可以总是使用绝对路径而不是相对路径:例如,文件:C:/config/services.xml或者classpath:/config/services.xml。但是,请注意,您正在将应用程序的配置耦合到特定的绝对位置。对于这样的绝对位置,通常最好保持间接——例如,通过在运行时针对JVM系统属性解析的“${…}”占位符。

The namespace itself provices 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.

命名空间本身支持import 指令特性。在Spring提供的XML名称空间(例如上下文和util名称空间)中,除了普通bean定义之外,还有其他配置特性。

The Groovy Bean Definition 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:

Groovy Bean定义DSL
作为外部化配置元数据的进一步示例,从Grails框架中可以知道,bean定义也可以在Spring的Groovy bean定义DSL中实现。通常,这样的配置位于.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(容器的使用)

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 requiredType), you can retrieve instances of your beans.

ApplicationContext是一个高级工厂的接口,能够维护不同bean及其依赖关系。通过使用T getBean(String name, Class requiredType)方法,您可以获取bean的实例。

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

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 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的context实现类(但也理解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和reader 委派相结合--例如,使用XmlBeanDefinitionReader,如下示例所示:

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:

您还可以为Groovy文件使用GroovyBeanDefinitionReader,如下例所示:

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上混合并匹配这样的reader委托,从不同的配置源读取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)提供了依赖注入来进行集成,允许您通过元数据声明(如autowiring 注解)对特定bean的依赖

你可能感兴趣的:(SpringFramework翻译_2Core Technologies(核心技术1.2系列))