1.2. Container Overview

目录

前言

1.2.1. Configuration Metadata

1.2.2. Instantiating a Container

1.2.3. Using the Container


前言

The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.

ApplicationContext接口作为Spring IoC容器的体现, 负责实例化,配置和组装所有的bean对象

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.

配置元数据以XML, java注解, 或者直接java代码的形式表示

It lets you express the objects that compose your application and the rich interdependencies between those objects.

它可以让你描述组成你应用的那些对象, 以及对象之间复杂的依赖关系

Several implementations of the ApplicationContext interface are supplied with Spring.

Spring提供了多个ApplicationContext接口的实现

In stand-alone applications, it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.

在独立的应用程序中, 通常创建一个ClassPathXmlApplicationContext或者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.

尽管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.

在大多数的应用场景中, 用户代码不需要初始化一个或者多个Spring IoC容器。

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

例如:在web应用的场景中, 通常web.xml文件中简单的差不多8行样板xml描述就足够了

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.

如果你使用的IDE是sts,你只需要简单点几个鼠标或者按键就可以配置出这样的样板配置。

The following diagram shows a high-level view of how Spring works.

下图显示了 Spring 的工作原理的高级视图。

img

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.

您的应用程序类与配置元数据结合在一起,以便在创建和初始化ApplicationContext之后,您将具有完全配置且可执行的系统或应用程序。

1.2.1. Configuration Metadata

As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata.

如上图所示, Spring IoC 容器使用一种形式的配置元数据。

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 容器如何实例化,配置和组装应用程序中的对象。

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.

Spring configuration consists of at least one and typically more than one bean definition that the container must manage.

由容器管理的bean通常至少有一个以上在Spring配置文件中定义

XML-based configuration metadata configures these beans as <bean/> elements inside a top-level <beans/> element.

基于 XML 的配置元数据将这些 bean 配置为顶级<beans/>元素内的<bean/>元素。

Java configuration typically uses @Bean -annotated methods within a @Configuration class.

Java 配置通常在@Configuration类中使用@Bean注解的方法。

These bean definitions correspond to the actual objects that make up your application.

这些 bean 定义对应于组成应用程序的实际对象。

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.

通常,您定义服务层对象,数据访问层对象(DAO),表示层对象(例如 Struts Action实例), 基础架构对象例如Hibernate中的 SessionFactories,JMS中的 Queues等

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.

通常,不会在容器中配置细粒度的域对象,因为 DAO 和业务逻辑通常负责创建和加载域对象。

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.

但是,您可以使用 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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
​
    <bean id="..." class="...">  (1) (2)
        <!-- 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) The id attribute is a string that identifies the individual bean definition.

  • (1) id属性是标识单个 bean 定义的字符串。

  • (2) The class attribute defines the type of the bean and uses the fully qualified classname.

  • (2) 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。有关更多信息,请参见Dependencies。

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");

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.

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 PetStoreServiceImpl class and two data access objects of the types JpaAccountDao and JpaItemDao (based on the JPA Object-Relational Mapping standard).

在前面的示例中,服务层由PetStoreServiceImpl类和两个类型为JpaAccountDao和JpaItemDao的数据访问对象组成

The property name element refers to the name of the JavaBean property, and the ref element refers to the name of another bean definition.

property name元素指向 JavaBean 属性的名称, 而ref元素指向另一个 bean 定义

This linkage between id and ref elements expresses the dependency between collaborating objects. For details of configuring an object’s dependencies, see Dependencies.

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.

使 bean 定义跨越多个 XML 文件可能很有用。通常,每个单独的 XML 配置文件都代表体系结构中的逻辑层或模块。

You can use the application context constructor to load bean definitions from all these XML fragments.

您可以使用应用程序上下文构造函数从所有这些 XML 片段中加载 bean 定义。

This constructor takes multiple Resource locations, as was shown in the previous section.

该构造函数具有多个Resource位置, 就像前面的例子那样

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:

或者,使用一个或多个<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 .

在前面的示例中,从三个文件services.xml,messageSource.xml和themeSource.xml加载了外部 bean 定义。

All location paths are relative to the definition file doing the importing, soservices.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.

所有位置路径都相对于进行导入的定义文件,因此services.xml必须与进行导入的文件位于同一目录或 Classpath 位置,而messageSource.xml和themeSource.xml必须位于导入文件位置下方的resources位置

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.

根据 Spring Schema,导入的文件的内容(包括顶级<beans/>元素)必须是有效的 XML bean 定义。

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.

命名空间本身提供了导入指令功能。 Spring 提供的一系列 XML 名称空间(例如context和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:

作为外部化配置元数据的另一个示例,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

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 定义并访问它们,如以下示例所示:

// 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与阅 Reader 委托组合,例如,对于 XML 文件,是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:

您还可以将GroovyBeanDefinitionReader用于 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.

然后,您可以使用getBean来检索 bean 的实例。

The ApplicationContext interface has a few other methods for retrieving beans, but, ideally, your application code should never use them.

ApplicationContext接口还有其他几种检索 bean 的方法,但是理想情况下,您的应用程序代码不应该使用它们。

Indeed, your application code should have no calls to the getBean() method at all and thus have no dependency on Spring APIs at all.

实际上,您的应用程序代码应该一点也不调用getBean()方法,因此完全不依赖于 Spring API。

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

例如,Spring 与 Web 框架的集成为各种 Web 框架组件(例如控制器和 JSFManagement 的 Bean)提供了依赖注入,使您可以通过元数据(例如自动装配)声明对特定 Bean 的依赖。

译者注: 所以需要使用Spring的bean的时候使用依赖注入就好了, 不需要自己单独去调用Spring的getBean()方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值