zoukankan      html  css  js  c++  java
  • 翻译-1.2 容器概述

    翻译自:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-basics

    原文

    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.

    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是定义配置元数据的传统形式,我们仍然可以让容器使用java注解或者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 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.

    大多数的应用场景中,用户代码已经明确地表示了不需要初始化一个或者多个springioc容器。
    例如:在web应用的场景中,典型的,web.xml文件中简单的8行样板xml描述就足够了(见1.15中关于Convenient ApplicationContext Instantiation for Web Applications的描述)。
    加入你使用的IDE是sts,你只需要简单点几个鼠标或者按键就可以配置出这样的样板配置。

    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创建并初始化了之后,程序就是完全配置的并且是可执行的。

    image

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

    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.

    • 基于注解的配置:spring2.5引入的支持

    • 基于java代码的配置:spring3.0开始,

    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的配置由最少一个通常多于1个的bean definition组成,这些bean definition都由spring容器管理。
    基于xml的配置方式是将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.

    这些bean definition和组成你应用的实际对象一一对应。
    通常,你会定义service层对象,dao层,展现层对象,例如Struts Action实例,基础组件对象,例如Hibernate SessionFactories, JMS Queues等等。
    通常,不会在容器中配置比较细的domain对象,因为通常由dao层或者业务逻辑来创建和加载domain对象。
    你也可以使用spring整合AspectJ来配置那些ioc容器之外创建的对象。详细信息请看5.10.1

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

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

    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.

    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构造器的location path/paths是资源位置的字符串表达式;容器可以从各种的外部资源中加载配置元数据,比如:本地文件系统,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的抽象(也叫Resources),这为从URI语法中定义的位置读取输入流提供了一种方便的机制。
    资源路径用于构建应用上下文,具体的描述在2.7中。

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

    service层配置文件例子:

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

    dao层例子:

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

    在之前的例子里,service层由PetStoreServiceImpl类和俩个dao层的对象JpaAccountDao和JpaItemDao(基于JPA对象关系映射标准)组成。
    name元素指向了bean中属性的名字,而ref元素指向了别的bean definition。
    id和ref这俩个元素之间的联系传达了组合对象这件的依赖关系。
    更多的关于配置对象间依赖关系的细节,请参阅1.4

    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 definition拆分到多个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:

    你可以使用ApplicationCOntext的构造函数来从这些xml片段加载bean definition信息。
    构造器可以像1.2.2小节介绍那样使用多个资源位置。
    也可以使用元素从其他文件中加载bean definition,像下面的例子介绍的那样:(这样构造函数就可以只加载一个xml文件了)

    <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 element, must be valid XML bean definitions, according to the Spring Schema.

    例子中,外部的(相当于当前文件)bean definition被从三个文件加载过来: services.xml, messageSource.xml, and themeSource.xml。
    (例子中配的)所有的位置路径都是做导入操作的这个文件的相对路径,也就是services.xml 必须是和他同一个目录/类路径位置,
    而messageSource.xml and themeSource.xml 的资源位置必须below导入文件的位置。
    正如你看到的,开头位置的那个【/】是被忽略的;但是鉴于这些路径都是相对的,最好是不在开头使用【/】。
    导入的内容,包括顶级元素都必须是符合spring语法的有效的xml bean definition。

    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.

    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.

    namespace提供了import指令功能。除了简单的bean definition指令外,其他的配置指令也可以通过选择spring提供的xml namespaces来获得。

    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:

    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.

    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.

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

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

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

    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 definition。

    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接口还有一些其他的方法可以用来检索beans,但是最好不要使用它们。
    实际上,您的应用程序代码根本不应该调用方法【getbean】,因此完全不依赖于SpringAPI。
    例如:spring和web框架的整合就为不同的web框架组成部分提供了依赖注入,比如各种controllers和JSF管理的beans,让你可以通过元数据(比如autowiring注解)在bean上声明一个依赖。

    补充

  • 相关阅读:
    Linux 删除用户时报错:userdel: user zhoulijiang is currently used by process 1
    mysqldump: Error: Binlogging on server not active
    Java并发编程:阻塞队列
    Java并发编程:线程池的使用
    Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
    Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition
    Java常用排序算法/程序员必须掌握的8大排序算法
    KMP算法
    Java NIO:浅析I/O模型
    Java NIO:NIO概述
  • 原文地址:https://www.cnblogs.com/po-shi/p/10932176.html
Copyright © 2011-2022 走看看