上一节 1.1. Introduction to the Spring IoC Container and Beans

目录

下一节 1.3. Bean Overview

文章目录

  • 1.2. Container Overview
    • 1.2.1. Configuration Metadata
    • 1.2.2. Instantiating a Container
      • Composing XML-based Configuration Metadata
      • The Groovy Bean Definition DSL
    • 1.2.3. Using the Container

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.

ApplicationContext 接口相当于一个Spring Ioc容器,并且负责实例化、配置、组装 beans。
容器通过读取配置元数据的说明,来确定实例化、配置和组装 具体的对象。
配置元数据可以通过XML、Java标签或者Java代码实现。
通过元数据,你可以表达构建你的应用系统的对象,以及这些对象职期间丰富的依赖关系。
[WORD]
1. represents
[B]
英 [ˌreprɪˈzents]   美 [ˌreprɪˈzents]
v.代表;作为…的代言人;维护…的利益;等于;相当于;意味着
represent的第三人称单数[W]
1: to bring clearly before the mind : PRESENT
// a book which represents the character of early America
【代表美国早期特征的一本书】
2: to serve as a sign or symbol ofthe flag represents our country
// the flag represents our country【国旗代表我们的国家】
...
*9: to serve as a specimen, example, or instance of
* * *
2. instructions
[B]
英 [ɪnˈstrʌkʃənz]   美 [ɪnˈstrʌkʃənz]
n.
用法说明;操作指南;指示;命令;吩咐;(计算机的)指令
instruction的复数[W]
1
* a: instructions plural : an outline or manual of technical procedure : DIRECTIONS
b: a direction calling for compliance : ORDER —usually used in plural
// had instructions not to admit strangers【指示不要接待陌生人】
c: a code that tells a computer to perform a particular operation
d: PRECEPTprevailing cultural instructions2: the action, practice, or profession of teaching[GRAMMAR]
1. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.
主干:The container gets its instructions ... by reading configuration metadata.
on what 修饰 instructions2. It lets you express the objects that compose your application and the rich interdependencies between those objects.
主干: t lets you express the objects and interdependencies .
that compose ... 修饰 objects , 

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标签或者代码作为元数据格式,
通过提供少量的XML配置文件来启用对这些其他元数据格式的支持。
[WORD]
1. implementations
[B]
英 [ˌɪmplɪmɛnˈteɪʃənz]   美 [ˌɪmpləmɛnˈteɪʃənz]
实现;实施;实现工具;实作
[W]
: an act or instance of implementing something : the process of making something active or effective
// implementation of a new policy/law 【实施新政策/法律】
// The Vatican returned the revised text to the bishops for implementation.
【梵蒂冈将修订后的文本退还给主教以执行。】
— Rita Ferrone
// That standard, which defines how much ozone is unhealthy, was set in 1997,
but its implementation was delayed by legal challenges.
【该标准于1997年制定,该标准定义了多少臭氧不健康,但由于法律挑战而推迟了其实施。】
— Cheryl Hogue----2. supplied
[B]
英 [səˈplaɪd]   美 [səˈplaɪd]
adj.备有…的;有…提供的
v.(尤指大量)供应,供给,提供
supply的过去分词和过去式
[W]
1
a: the quantity or amount (as of a commodity) needed or available
【需要或可获得的数量或金额(作为商品)】
// beer was in short supply in that hot weather
【在那个炎热的天气里啤酒供不应求】
— Nevil Shute
b: PROVISIONS, STORES —usually used in plural
c: a member of the clergy filling a vacant pulpit temporarily
dobsolete : REINFORCEMENTS —often used in plural
* 2: the act or process of filling a want or need
【满足需求的行为或过程】
// engaged in the supply of raw materials to industry
【从事工业原料的供应】
3: the quantities of goods or services offered for sale at a particular time or at one price
【在特定时间或以一个价格出售的商品或服务的数量】
4: something that maintains or constitutes a supply----3. instruct
[B]
英 [ɪnˈstrʌkt]   美 [ɪnˈstrʌkt]
v.指示;命令;吩咐;教授,传授(技能等);告知;通知
[W]
1: to give knowledge to : TEACH, TRAIN
2: to provide with authoritative information or advice
// the judge instructed the jury【法官指示陪审团】
* 3: to give an order or command to : DIRECT[GRAMMAR]
1. 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.
主干:you can instruct the container
to use ... 和 by providing... 都是用来修饰 指示容器 这件事情

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实例化)。
如果您使用Eclipse Spring Tools(基于Eclipse的开发环境),则只需单击几下鼠标或键盘操作
就可以轻松创建此样板配置。[WORD]
1. scenarios
[B]
英 [sɪˈnɑːrɪəʊz]   美 [sɪˈnɛrioʊz]
n.设想;方案;预测;(电影或戏剧的)剧情梗概
scenario的复数----2. explicit
出现67次
[B]
英 [ɪkˈsplɪsɪt]   美 [ɪkˈsplɪsɪt]
adj.清楚明白的;易于理解的;(说话)清晰的,明确的;直言的;坦率的;直截了当的;不隐晦的;不含糊的----3. boilerplate
[B]
英 [ˈbɔɪləpleɪt]   美 [ˈbɔɪlərpleɪt]
n.(可供模仿的)样板文件,文件范例
[W]
1: syndicated material supplied especially to weekly newspapers in matrix or plate form
2
* a: standardized text
b: formulaic or hackneyed languagebureaucratic boilerplate
3: tightly packed icy snow【密密麻麻的冰雪】

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被创建和初始化后,您将获得一个配置好的可以运行的系统和应用。[WORD]
1. combined
出现10次
[B]
英 [kəmˈbaɪnd]   美 [kəmˈbaɪnd]
adj.联合的;共同的;总计的;总共的
v.(使)结合,组合,联合,混合;兼有;兼备;使融合(或并存);同时做(两件或以上的事);兼做;兼办
combine的过去分词和过去式

Figure 1. The Spring IoC container

1.2.1. Configuration Metadata

1.2.1 配置元数据

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容器实例化、
配置和组装应用中的对象。
[WORD]
1. consumes
[B]
英 [kənˈsjuːmz]   美 [kənˈsuːmz]
v.
消耗,耗费(燃料、能量、时间等);吃;喝;饮;使充满(强烈的感情)
consume的第三人称单数[W]
1: to do away with completely : DESTROY
since 14th century
// Fire consumed several buildings.【大火烧毁了几座建筑物。】
2
a: to spend wastefully : SQUANDE
// Rconsumed his inheritance on luxuries【把他的遗产花在奢侈品上】
b: USE UP
// Writing consumed much of his time.【写作耗费了他的大部分时间。】
3
a: to eat or drink especially in great quantity
// consumed several bags of pretzels【吃了几袋椒盐卷饼】
b: to enjoy avidly : DEVOUR
// … mysteries, which she consumes for fun …
— Eden Ross Lipson
4: to engage fully : ENGROSS
// consumed with curiosity【充满好奇心】
5: to utilize as a customer
// consume goods and services【消费商品和服务】

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容器的关键概念和特征的方法。
1. intuitive
英 [ɪnˈtjuːɪtɪv]   美 [ɪnˈtuːɪtɪv]
adj.凭直觉得到的;直觉的;有直觉力的;易懂的;使用简便的
[W]1: possessing or given to intuition or insight
// an intuitive mind
2
a: known or perceived by intuition : directly apprehended
since 1645
// had an intuitive awareness of his sister's feelings【对姐姐的感觉有直观的认识】
b: knowable by intuition
// intuitive truths【直观的真相】
c: based on or agreeing with intuition
// intuitive responses
// makes intuitive sense
* d: readily learned or understood
// software with an intuitive interface【具有直观界面的软件】
3: knowing or perceiving by intuition----2. convey
[B]
英 [kənˈveɪ]   美 [kənˈveɪ]
v.表达,传递(思想、感情等);传送;运送;输送
[W]
1
a: to bear from one place to another【从一个地方到另一个地方】
especially : to move in a continuous stream or mass【特别指:连续不断、大量的移动】
b: to impart or communicate by statement, suggestion, gesture, or appearance
// struggling to convey his feelings【努力表达他的感情】
c: to transfer or deliver (something, such as property) to another especially by a sealed writing
* d: to cause to pass from one place or person to another
// convey a message【传达信息】
e(1)archaic : STEAL 【古代:偷窃】
(2)obsolete : to carry away secretly【过时:偷偷地运走】
2 obsolete : LEAD, CONDUCT【过时:】
since 14th century----3. features
出现49次
[B]
英 [ˈfiːtʃəz]   美 [ˈfiːtʃərz]
n.特色;特征;特点;面容的一部分(如鼻、口、眼);(报章、电视等的)特写,专题节目
v.以…为特色;由…主演;以…为主要组成;起重要作用;占重要地位
[W]
noun
1
a: the structure, form, or appearance especially of a person【尤指人的结构,形式或外表】
// a man of large feature【a man of large feature】
since 14th century
b: obsolete : physical beauty【过时:漂亮】2
a: the makeup or appearance of the face or its parts
// stern of feature even when he smiled【即使在他微笑的时候,也很严峻】
b: a part of the face : LINEAMENT
// a person with Asian features【一个具有亚洲面孔的人】3
a: a prominent part or characteristic
// Pine trees were a feature of the landscape.【松树是景观的特征。】
b: any of the properties (such as voice or gender) that are characteristic of a grammatical element (such as a phoneme or morpheme)
especially : one that is distinctive4: a special attraction: such as
a: a featured motion picture
b: a featured article, story, or department in a newspaper or magazine
// An account of the fire was the feature in the Sunday newspaper.【一场火灾事故在周日报纸上特别显眼】
c: something offered to the public or advertised as particularly attractive
// one of the car's most popular features【汽车最受欢迎的功能之一】verb 1: chiefly dialectal : to resemble in features【主要是方言的:类似于特征】since about 17552: to picture or portray in the mind : IMAGINE 【在脑海中描绘或描绘】3
a: to give special prominence to【使特别突出】
// the exhibit features local artists【展览突出了当地的艺术家特点】
b: to have as a characteristic or feature
// a menu featuring many options【具有许多选项的菜单】

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 IoC容器本身与实际写入此配置元数据的格式完全分离。
近来,许多开发者选择使用基于Java的配置文件来为他们的Spring应用生成Spring容器。
[GRAMMAR]
1. The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written.
主干:The Spring IoC container is decoupled from the format

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容器中使用其他形式的元数据的信息,可以参考:
* 基于Java标签的配置方法:Spring 2.5 引入支持 Java标签的配置元数据;
* 基于Java代码的配置方法:从Spring 3.0开始,Spring JavaConfig项目称为 Spring核心框架的一部分,并提供了很多的新特性。
通过JavaConfig,你不但可以通过XML文件还可以使用Java代码的方式来定义beans从外部注入你的应用类。
要使用这些新功能,请参阅@ Configuration,@ Bean,@ Import和@DependsOn注释。
[GRAMMAR]
you can define beans external to your application classes by using Java rather than XML files.
主干:you can define beans ... by using ...
external to your application classes 修饰beans

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 definition 。
在基于XML文件的元数据,顶层元素<beans/>中,这些beans被定义成 <bean/> 元素。
在Java代码的配置方式中,一般来说在一个@Configuration类中,使用@Bean-annotated
标签的方法来定义beans。

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 definitions 相当于组成您应用的实际对象。
一些典型的例子包括,你定义的 service层的对象、数据访问层对象(DAOs)、
数据展现层对象例如Struts Action实例、基础层对象如Hibernate的SessionFacories、
JMS Queues等。
通常,不会在容器中配置细粒度的域对象,因为创建和加载域对象通常是DAO和业务逻辑层的责任。
但是,您可以使用Spring与AspectJ的集成来配置在IoC容器控制之外创建的对象。
请参阅使用AspectJ与Spring依赖注入域对象
[WORD]
1. correspond
出现46次
[B]
英 [ˌkɒrəˈspɒnd]   美 [ˌkɔːrəˈspɑːnd]
v.相一致;符合;类似于;相当于;通信
[W]
1
a: to be in conformity or agreement
since 1529:Middle French or Medieval Latin; Middle French correspondre,
from Medieval Latin correspondēre, from Latin com- + respondēre to respond
// … the ideal failed once again to correspond with the reality …
【理想再次失败与现实相对应】
— James R. Sutherland
b: to compare closely : MATCH —usually used with to or with
// The number of ballots cast should correspond to the number of people present.
【投票数应与在场人数相对应。】
c: to be equivalent or parallel
// In some countries, the role of president corresponds to that of prime minister.
【在某些国家/地区,总统的职责与总理的职责相对应。】2: to communicate with a person by exchange of letters----2. typically
出现51次
[B]
英 [ˈtɪpɪkli]   美 [ˈtɪpɪkli]
adv.通常;一般;典型地;具有代表性地;不出所料;果然
[W]
1: on a typical occasion : in typical circumstances
// typically, members of our staff receive little … recognition
【通常,我们的员工很少得到……认可】
— Brendan Gill2: in a typical manner
// typically American【典型的美国人】----
3. fine-grained
[B]
英 [faɪn ɡreɪnd]   美 [faɪn ɡreɪnd]
adj.细粒的;有细密纹理的
[W]
1: producing images of low graininess so that considerable enlargement
without undue coarseness is permitted
—used of a photographic developer2or less commonly fine-grained \ ˈ⸗¦⸗ \ : characterized by comparatively fine graininess —used of a photographic image or photographic emulsion

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="...">  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.
  2. The class attribute defines the type of the bean and uses the fully qualified classname.
1. id属性是用来标记独一无二的bean definition的一个字符串。
2. class属性定义了bean的类型,并使用了完整可用的类名。
[WORD]
1. qualified
[B]
英 [ˈkwɒlɪfaɪd]   美 [ˈkwɑːlɪfaɪd]
adj.具备…的学历(或资历);具备…的知识(或技能);符合资格;有限度的;有保留的;有条件的
v.取得资格(或学历);合格;使合格;使具备资格;有权,使有权(做某事)
qualify的过去分词和过去式
[W]
1
* a: fitted (as by training or experience) for a given purpose : COMPETENT
b: having complied with the specific requirements or precedent conditions (as for an office or employment) : ELIGIBLE
2: limited or modified in some way

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

1.2.2. 实例化一个容器

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 等。[GRAMMAR]
主干:The location path or paths are resource stringssupplied to ... 修饰 The location path or paths , that let...  修饰 resource strings, such as ... 修饰 external resources

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语法中定义的位置读取InputStream。
特别是,在应用程序上下文和资源路径中描述,资源路径用于构造应用程序上下文。
[WORD]
1. particular
出现59次
[B]
英 [pəˈtɪkjələ(r)]   美 [pərˈtɪkjələr]
adj.专指的,特指的(与泛指相对);不寻常的;格外的;特别的;讲究;挑剔
n.(正式记下的)细节,详情;详细资料;详细介绍材料
[W]
1: of, relating to, or being a single person or thing
// the particular person I had in mind
【我想到的那个特别的人】2: of, relating to, or concerned with details
// gave us a very particular account of the trip
【给了我们一个非常特别的旅程】3
a: distinctive among other examples or cases of the same general category : notably unusual
// suffered from measles of particular severity
【患有严重程度的麻疹】
// This computer program will be of particular interest to teachers.
【该计算机程序将对教师特别感兴趣。】
b: being one unit or element among others
// particular incidents in a story
【故事中的特定事件】4
a: concerned over or attentive to details : METICULOUS
【一丝不苟】
// a very particular gardener
【一个非常尽职的园丁】
b: nice in taste : FASTIDIOUSS
【挑剔的】
// he's very particular about her clothes.
【他很挑剔她的服装】
c: hard to please : EXACTING
// never loses patience even with the most particular customers
【即使是最特殊的客户也永远不会失去耐心】5
a: denoting an individual member or subclass in logic
b: affirming or denying a predicate to a part of the subject —used of a proposition in logic
// "some men are wise" is a particular affirmative
【“有些人很聪明”是一种特殊的肯定】6 obsolete : PARTIAL【过时:部分】

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/beanshttps://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/beanshttps://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类 和 两个数据访问层对象(JpaAccountDao and JpaItemDao 基于JPA技术)
组成。property name 元素指的是 JavaBean属性的名称, ref属性表示 引用另外一个bean definition。id和ref元素之间的关联
表示了相关联对象之间的依赖关系。为进一步了解对象依赖关系的配置方法,请查看 Dependencies 章节内容。

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 definitions分布在不同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片段中使用 application context 构造函数加载 bean definitions 。
正如前面章节见到的,这个构造函数从各种类型的Resource 位置获取数据。
或者,我们也可以使用一个或多个 <import/> 元素,从其他的文件中加载 bean definitions。
下面的例子说明如何做到这一点:

<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 definitions从下面3个文件中被加载进来:services.xml, messageSource.xml, and themeSource.xml。
所有本地路径都相对于进行导入定义文件的位置,因此services.xml必须与进行
导入的文件位于同一目录或类路径位置,而messageSource.xml和themeSource.xml
必须位于该位置下方的资源位置。
如您所见,正斜杠被忽略。
但是,鉴于这些路径是相对的,最好不要使用斜线。
导入的文件的内容(包括顶级<beans />元素)必须是基于Spring Schema的
有效XML bean definitions。

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)使用此参考,
运行时解析过程会选择``最近的''类路径根目录,然后查看其父目录。
Classpath配置的更改可能导致选择其他错误的目录。
您可以使用完全限定的资源位置来代替相对路径:
例如,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名称空间他配置功能
-例如,context和util名称空间。

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 definitions同样也可以通过
Spring的Groovy Bean Definition 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 definitions 相同,甚至能够支持 Spring的XML配置命名空间。
它还允许通过importBeans指令导入XML bean定义文件。

1.2.3. Using the Container

1.2.3. 使用容器

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是一个先进的工厂接口能够维护不同beans及其他们之间依赖关系的注册。
通过使用 getBean 方法,你可以获取
您的beans实例。

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

ApplicationContext能够让您读取并访问 bean definitions,下面是具体案例:

// 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-aware(同样也能够理解XML的BD)。
下面是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 读取XML文件。
1. variant
出现23次
[B]
英 [ˈveəriənt]   美 [ˈveriənt]
n.变种;变体;变形
adj.变异的;不同的,相异的,不一致的;多样的;易变的,不定的
[W]
1: manifesting variety, deviation, or disagreement
2: varying usually slightly from the standard form
since 14th century :Middle English variaunt, borrowed from Anglo-French variant, borrowed from Latin variant-, varians "variegated, various,"
// variant readings
// variant spellings
3obsolete : VARIABLE

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上混合和匹配此类reader 委托,
从不通的配置源上 读取 bean definitions。
1. diverse
[B]
英 [daɪˈvɜːs]   美 [daɪˈvɜːrs]
adj.不同的;相异的;多种多样的;形形色色的
[W]
1: differing from one another : UNLIKE
// people with diverse interests【有不同兴趣的人】
2: composed of distinct or unlike elements or qualities
// a diverse population【多样化的人口】

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()方法,因此完全不直接依赖Spring API。
例如,整合了Web的Spring框架 为各种Web框架组件
(例如c ontrollers and JSF-managed 的Bean)提供了依赖注入,
使您可以通过元数据声明对特定Bean的依赖(例如一个 autowiring 的标签)[WORD]
1. retrieve
出现16次
[B]
英 [rɪˈtriːv]   美 [rɪˈtriːv]
v.取回;索回;检索数据;扭转颓势;挽回;找回
[W]
verb
1: to locate and bring in (killed or wounded game)
since 1814: Middle English retreven, from Anglo-French retrueve-, present stem of retrover to find again
2: to call to mind again
3: to get back again : REGAIN
4
a: RESCUE, SALVAGE
b: to return (something, such as a ball or shuttlecock that is difficult to reach) successfully
5: RESTORE, REVIVE
// his writing retrieves the past【他的作品还原了过去】
6: to remedy the evil consequences of : CORRECT
7: to get and bring backespecially : to recover from storage
// retrieve information【检索信息】
noun
1: RETRIEVAL【数据检索】
since 1658
2: the successful return of a ball that is difficult to reach or control (as in tennis)
【难以到达或控制的回球(如网球中)】

1.2. Container Overview相关推荐

  1. Kata Container — Overview

    目录 文章目录 目录 传统容器的安全问题 Kata Container 软件架构 轻量化虚拟机 QEMU Guest Kernel Guest image (rootfs)Root filesyste ...

  2. 【翻译 Spring 5.0.4.RELEASE】1.The IoC container

    其中最重要的是Spring框架的控制反转(IoC)容器. Spring框架的IoC容器的全面处理紧随其后,全面涵盖了Spring的面向方面编程(AOP)技术. Spring框架拥有自己的AOP框架,这 ...

  3. 云计算与云原生技术系列文章

    目录 文章目录 目录 云计算 云原生 云原生思想 容器技术 Docker containerd Kata Container APIGW ETCD 服务治理 - Service Mesh FaaS O ...

  4. Beats:Beats 入门教程 (二)

    这篇文章是 "Beats 入门教程 (一)"的续篇.在上一篇文章,我们主要讲述了 Beats 的一些理论方面的知识.在这篇文章中,我们将具体展示如何使用 Filebeat 及 Me ...

  5. Spring的下载及目录结构

    Spring的下载及目录结构 1.使用浏览器访问Spring的官方下载地址(官网地址:Spring FrameworkLevel up your Java code and explore what ...

  6. Spring框架文档(二 )

    @[TOC](文章目录) 原文英文链接: https://docs.spring.io/spring/docs/5.2.3.BUILD-SNAPSHOT/spring-framework-refere ...

  7. Spring Framework Core IOC

    Core IoC Container 依赖注入的方式如下: 通过构造函数参数 通过工厂方法的参数 从构造或者工厂方法返回的对象实例上设置的属性 这个过程通过直接使用类的构造或者类似服务定位器模式的机制 ...

  8. Mix XDI V1.1 - Golang DI、IoC 依赖注入容器

    OpenMix 出品:https://openmix.org Mix XDI DI.IoC 容器 DI, IoC container Overview 一个创建对象以及处理对象依赖关系的库,该库可以实 ...

  9. Performance overview: Unixbench results on Container and VM, and seccomp

    文章目录 Conclusions Test Details Purpose Tools Unixbench Why to use Test cases Hardware environment Tes ...

  10. Container Networking Interface Specification

    转自:https://github.com/containernetworking/cni/blob/master/SPEC.md Version This is CNI spec version 0 ...

最新文章

  1. 一个「PPT」框架,让超大模型调参变简单:清华刘知远、黄民烈团队力作
  2. 借力英伟达打造车规L3智能驾驶大脑,揭开德赛西威量产的“秘密”
  3. numpy数组ndarray如何对每个元素取绝对值,然后生成原数组的绝对值数组
  4. HeadFirst设计模式(四) - 工厂模式之1 - 简单工厂
  5. 里海水位上升的原因_汽轮机真空下降的原因及处理
  6. 【今日头条】头条号图文发布页面的“扩展链接”是干嘛用的?
  7. go-ethereum-code-analysis 以太坊源码分析
  8. 论文翻译《Object-Level Ranking: Bringing Order to Web Objects》
  9. C: City----逆向并查集
  10. SpringBoot项目集成Mybatis Plus(五)条件构造器
  11. ibm邮件怎么撤回_怎么申请邮箱?163邮箱如何注册使用?
  12. PAT 乙级 1046. 划拳(15) Java版
  13. HCIE-Security Day38:理论学习:信息安全管理
  14. Flask 的 数据库连接 与 DBUtils 数据库连接池
  15. java中do until_RxJava—takeUntil实践
  16. 锁相环倍频原理简要分析
  17. Ububtu 解压zip分卷文件
  18. 【bzoj1050】[HAOI2006]旅行comf
  19. Excel中序号自动填充
  20. 【LOJ3124】「CTS2019」氪金手游

热门文章

  1. 如何用python来打印一个三角形
  2. Swift - 去处图片的白色、黑色背景(使UIImage背景透明)
  3. 邮件开头结尾一些不同的表达
  4. Spring漫画学习笔记(二) 什么是BeanFactory
  5. 苹果cms模板_苹果cmsv10高端模板有哪些?
  6. 【网页设计自习室#004】网页页面导航栏(header头部)的设计
  7. 元宇宙时代的5大风险
  8. OEM/ODM/OBM
  9. 基于 DirectShow 实现 SourceFilter 常见问题分析
  10. 上“低代码”半年,30名程序员被裁,CTO离职!