原文链接:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html
spring version 5.3.9
上一篇:1.1对Spring IoC 和Bean的简明介绍
org.springframework.context.ApplicationContext 接口代表的是Spring IoC 容器,他负责初始化,配置,装配Bean。容器从配置元数据中获取对象的初始化,配置,装配信息。配置可以是XML,注解或者Java代码。这使得你可以描述你的应用和各对象间各种复杂依赖。
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.
Spring中ApplicationContext
接口的还有几个实现。在独立应用中,通常使用ClassPathXmlApplicationContext
或 FileSystemXmlApplicationContext
创建实例。XML是传统的配置方式,另外你还可以用java 注解和代码配置容器,这样可减少XML的配置。
Several implementations of the
ApplicationContext
interface are supplied with Spring. In stand-alone applications, it is common to create an instance ofClassPathXmlApplicationContext
orFileSystemXmlApplicationContext
. 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.
在大多数应用程序场景中,实例化SpringIOC容器的一个或多个实例不需要显式代码。例如,在web应用程序场景中,应用程序的web.XML文件中的一个简单的八行左右web.xml文件
就足够了(请参见 Convenient ApplicationContext Instantiation for Web Applications)。如果您使用Spring Tools for Eclipse (一个支持Eclipse的开发环境),只需点击几下鼠标或按键,就可以轻松创建这个样板配置。
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如何工作的简要视图。您的应用程序类与配置元数据相结合,以便在创建和初始化ApplicationContext后,拥有一个完全配置且可执行的系统或应用程序。
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.
Figure 1. The Spring IoC container
如图所示,SpringIOC 容器使用固定模板的配置。此配置数据表示应用程序开发人员告知Spring容器如何进行实例化、配置和组装应用程序中的对象。
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.
配置通常是一个简明的XML格式,本章大部分内容讲述的是SpringIOC容器的关键概念和特性。
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 容器本身是与配置的格式解耦。目前,许多开发人员都是用java代码进行配置。 |
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 容器,参考:
Annotation-based configuration: Spring 2.5 介绍了基于注解的配置
Java-based configuration: Spring 3.0 以后,许多的特性由Spring Java 代码配置。 因此,你可以使用Java 而不是XML文件定义Bean,具体参考 @Configuration
, @Bean
, @Import
, @DependsOn
。
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 的配置由至少一个,通常是多个由容器管理的Bean 的定义。基于XML的配置文件在
元素下面使用 @Bean 的注解方法,并配置一个@Configuration标注的配置类。
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.
这些bean定义对应着构成应用程序的实际对象。通常来说,你可以定义你的业务处理层,就是service 层;数据访问层,dao层;展示层,就像Struts 框架里面的Action 一样;基础的对象,比如Hibernate 的 SessionFactories
, JMS 的 Queues 等等。通常来说,不能配置 domain 实体类作为Bean,因为通常使用Dao和业务逻辑创建,加载domain对象。然而,你可以使用Spring 集成 AspectJ 配置IoC容器以外创建的对象。具体
可参考 Using AspectJ to dependency-inject domain objects with Spring.
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 HibernateSessionFactories
, JMSQueues
, 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.
下面试一个使用XML配置的结构的例子
The following example shows the basic structure of XML-based configuration metadata:
注1,id 属性是一个标志每个bean区分其他bean的String
注2,class 属性定义的是bean类型,使用全限定类名。
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. |
id
的值关联使用该对象的其他bean。本例没有引用其他bean作为bean的属性,可参考Dependencies 了解更多。
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.
传递给ApplicationContext构造方法的路径参数,是资源的地址,可让容器从各种外部资源加载配置数据,比如本地系统的文件,CLASSPATH 下文件,等等。
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 JavaCLASSPATH
, and so on.
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
在你学习的Spring IoC 容器之后,你可能想知道更多关于Spring 资源的概念,可参考 Resources 。他能提供方便的机制读取 InputStream ,比如通过URI 语法。而且,资源的路径用于构建 应用会话,在 Application Contexts and Resource Paths里有描述。
After you learn about Spring’s IoC container, you may want to know more about Spring’s |
下面是 serice 层对象的配置文件的例子:
The following example shows the service layer objects
(services.xml)
configuration file:
下面是dao层的配置文件实例:
The following example shows the data access objects
daos.xml
file:
在前面的例子中,service层有PetStoreServiceImpl
,数据访问层有 JpaAccountDao
和JpaItemDao
,这两个是基于JPA对象关系映射标准。name属性引用JavaBean属性的名称,指向元素引用另一个bean定义的名称。id和引用元素之间的链接表示协作对象之间的依赖关系。有关配置对象依赖项的详细信息,请参见 Dependencies。
In the preceding example, the service layer consists of the
PetStoreServiceImpl
class and two data access objects of the typesJpaAccountDao
andJpaItemDao
(based on the JPA Object-Relational Mapping standard). Theproperty name
element refers to the name of the JavaBean property, and theref
element refers to the name of another bean definition. This linkage betweenid
andref
elements expresses the dependency between collaborating objects. For details of configuring an object’s dependencies, see Dependencies.
组合基于XML的配置元数据 Composing XML-based Configuration Metadata
有时需要顶多多个XML文件。每一个独立的XML配置文件代表每一个逻辑层,或者结构中的模块。
你可以使用application context 的构造器加载多个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.
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 theelement to load bean definitions from another file or files. The following example shows how to do so:
在上面的例子中,定义了三个需要额外加载的文件: services.xml
, messageSource.xml
, 和themeSource.xml 。所有的文件路径和导入的文件应该保持一致,比如messageSource.xml
和themeSource.xml
必须在 resources
路径下。开始的斜杠是可以忽略的。但是,如果是相对路径,最好使用斜杠。被导入的文件,包括顶级 的
In the preceding example, external bean definitions are loaded from three files:
services.xml
,messageSource.xml
, andthemeSource.xml
. 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, whilemessageSource.xml
andthemeSource.xml
must be in aresources
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 levelelement, must be valid XML bean definitions, according to the Spring Schema.
可以但是不建议,关联文件的父文件夹用 【../】代替。这样做创建了独立于当前应用的文件依赖。特别地,这种关联对 classpath 来说并不推荐,比如
classpath:../services.xml,这在运行时处理会选择距离
classpath root最近的,并在其父文件夹中查找。
classpath 的配置的改变可能会导致选择不同,甚至错误的目录。
使用绝对路径总比相对路径好,比如: file:C:/config/services.xml
或者classpath:/config/services.xml 。但是,要知道这样会让你把应用配置和具体的绝对路径进行耦合。最好的做法是用
${…} 关联JVM系统属性
让各自保持独立。
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 You can always use fully qualified resource locations instead of relative paths: for example, |
命名空间本身提供的是导入指令的特性。Spring提供的一系列XML命名空间中提供了普通bean定义之外的更多配置特性 — 例如,context 和util 命名空间。
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
andutil
namespaces.
Groovy Bean定义的DSL The Groovy Bean Definition DSL
Bean的定义还可以是Spring 的 Groovy Bean Definition DSL , Grails框架里用到的。通常来说,".groovy" 的文件使用下面的结构实例:
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
}
}
}
这个配置风格很大程度上等同于XML的bean 配置,甚至支持Spring 的XML 配置的命名空间。也可以通过 importBeans
命令导入XML 的Bean 定义文件
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.
ApplicationContext
是高级工厂的接口,能够维护不同bean及其依赖项的注册表。通过使用 T getBean(String name, Class
ApplicationContext
接口让你获取到Bean 的定义和获取权限,例子如下:
The
ApplicationContext
is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. By using the methodT getBean(String name, Class
, you can retrieve instances of your beans.requiredType) 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 userList = service.getUsernameList();
如果是用 Groovy 配置,起步非常的简单。他有一个不同的上下文实现类,它是Groovy感知的(但也理解XML 定义)。以下示例显示Groovy配置:
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");
最灵活的变体是GenericApplicationContext与 读处理器 委托的组合 — 例如,使用XmlBeanDefinitionReader 读取XML文件,如下例所示:
The most flexible variant is
GenericApplicationContext
in combination with reader delegates — for example, withXmlBeanDefinitionReader
for XML files, as the following example shows:
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
你也可以使用GroovyBeanDefinitionReader
读取Groovy文件,例子如下:
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();
你可以在同一个ApplicationContext
混合并匹配Reader 委托,读取不同来源的配置。
你可以使用 getBean 重复获取你的Bean。ApplicationContext
接口有几个方法用于多次的获取 bean。但是,最理想的情况,你的应用代码不应该使用他们。你的应用代码根本不应该调用 getBean() 方法,因此你的代码不应该依赖Spring API。比如说,Spring集成web框架,提供的依赖注入到各种web框架组件中,比如控制器,JSF管理的Bean,这让你只要通过配置就可以声明依赖(比如java 注解)。
You can mix and match such reader delegates on the same
ApplicationContext
, reading bean definitions from diverse configuration sources.You can then use
getBean
to retrieve instances of your beans. TheApplicationContext
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 thegetBean()
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).
下一篇: 1.3Bean概述
Version 5.3.9
Last updated 2021-07-14 06:36:18 UTC