【Spring】Spring Framework Reference Documentation中文版1

Spring框架是一个轻量级的Java平台,提供全面的基础架构支持来帮助开发者聚焦于应用逻辑而非基础设施。它支持依赖注入、声明式事务管理、远程访问、数据持久化等多种功能,并且模块化设计使得可以根据需要选用特定组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于没有找到Spring Framework Reference Documentation的完全中文翻译。

为了自己学习,决定从今天开始翻译该篇英文大作。

我决定采用中英文混合的方式发布,暂时没有目录和索引链接。

纯手工翻译,不保证进度,但是我会努力将她翻译完,我不是外文系毕业的,如果有哪里翻译不正确的地方,请大家拍砖。

我知道网上有部分的译文,在此保证,如有部分雷同,纯属巧合。

 

Authors

Rod Johnson , Juergen Hoeller , Keith Donald , Colin Sampaleanu , Rob Harrop , Thomas Risberg , Alef Arendsen , Darren Davison , Dmitriy Kopylenko , Mark Pollack , Thierry Templier , Erwin Vervaet , Portia Tung , Ben Hale , Adrian Colyer , John Lewis , Costin Leau , Mark Fisher , Sam Brannen , Ramnivas Laddad , Arjen Poutsma , Chris Beams , Tareq Abedrabbo , Andy Clement , Dave Syer , Oliver Gierke , Rossen Stoyanchev , Phillip Webb , Rob Winch , Brian Clozel , Stephane Nicoll , Sebastien Deleuze

作者省略

 

版本号:4.3.4.RELEASE

 

Copyright ? 2004-2016

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

你可以使用本文档也可以将其发布给他人,但是对此你不能收取任何费用。当你发布或印刷该文档时,请保留此版权信息。

 

Part I. Overview of Spring Framework

第一部分,Spring框架的概述

 

The Spring Framework is a lightweight solution and a potential one-stop-shop for building your enterprise-ready applications. However, Spring is modular, allowing you to use only those parts that you need, without having to bring in the rest. You can use the IoC container, with any web framework on top, but you can also use only the Hibernate integration code or the JDBC abstraction layer. The Spring Framework supports declarative transaction management, remote access to your logic through RMI or web services, and various options for persisting your data. It offers a full-featured MVC framework, and enables you to integrate AOP transparently into your software.

Spring框架为你开发一个企业级应用提供了一个轻量级的一站式解决方案。并且Spring是模块化的工具,允许你单独使用其中一部分的组件而不需要在项目中加入其它不需要的组件。你可以在任何web框架上使用IOC容器,你也可以只使用Hibernate集成模块或JDBC抽象层。Spring框架支持声明式的事务管理,支持通过RMIweb service远程访问你的程序逻辑,支持通过各种方式持久化你的数据。Spring提供了一个全功能的MVC框架,并且允许你在程序中集成AOP组件。

 

Spring is designed to be non-intrusive, meaning that your domain logic code generally has no dependencies on the framework itself. In your integration layer (such as the data access layer), some dependencies on the data access technology and the Spring libraries will exist. However, it should be easy to isolate these dependencies from the rest of your code base.

Spring的设计目标是无侵入性,那就意味着你的逻辑代码通常不需要依赖框架本身。在你的程序中(例如数据访问层),一些对数据访问的依赖中有Spring的库。然而,应该很容易将这种依赖从你的其他代码中分离开来。

 

This document is a reference guide to Spring Framework features. If you have any requests, comments, or questions on this document, please post them on the user mailing list. Questions on the Framework itself should be asked on StackOverflow (see https://spring.io/questions).

这篇文档只是Spring框架特性的参考文档。如果你对这篇文档有任何要求、评论或问题,请使用读者邮箱给我们写信。关于框架本身的问题,请访问StackOverflow

 

1. Getting Started with Spring

开始Spring的旅程

 

This reference guide provides detailed information about the Spring Framework. It provides comprehensive documentation for all features, as well as some background about the underlying concepts (such as "Dependency Injection") that Spring has embraced.

这篇参考手册提供了Spring框架的详细信息。本文档对所有的特性提供了详尽的文档参考,并且也包括Spring最核心的底层内容,比如依赖注入。

 

If you are just getting started with Spring, you may want to begin using the Spring Framework by creating a Spring Boot based application. Spring Boot provides a quick (and opinionated) way to create a production-ready Spring based application. It is based on the Spring Framework, favors convention over configuration, and is designed to get you up and running as quickly as possible.

如果你刚刚开始学习Spring,你或许想通过建立一个Spring Boot的基本应用为起点开始使用Spring框架。Spring Boot提供了一个快捷的方式来建立一个基于Spring的应用。他是基于Spring框架的约定优于配置的准则,使得你可以尽快的让你的程序跑起来。

 

You can use start.spring.io to generate a basic project or follow one of the "Getting Started" guides like the Getting Started Building a RESTful Web Service one. As well as being easier to digest, these guides are very task focused, and most of them are based on Spring Boot. They also cover other projects from the Spring portfolio that you might want to consider when solving a particular problem.

你可以使用start.spring.io来生成一个基本的骨架,或者通过使用参考"Getting Started" guides中的一个教程比如开始创建一个REST福利风格的WebService程序。为了方便理解,这些教程都是任务驱动的,并且里面的大部分都是基于Spring Boot的。他们也涵盖了你可能会在处理某些特殊问题时会使用到的Spring的其他组件部分。

 

2. Introduction to the Spring Framework

Spring框架的介绍

 

The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.

Spring作为一个Java平台为了支持你开发应用提供了各种各样的基础控件。Spring关注了通用的部分以方便你可以专注于你的应用逻辑。

 

Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE.

Spring允许你通过POJO来创建你的应用,和使用对POJO无任何侵入的应用企业级服务。这种特性应用于Java SE编程模型和部分的Java EE中。

 

Examples of how you, as an application developer, can benefit from the Spring platform:

一些你做为应用开发者可以从Spring平台中获得便利。

 

    Make a Java method execute in a database transaction without having to deal with transaction APIs.

无需使用事务方面的API便能让你的Java方法可以在数据库事务中执行。

    Make a local Java method a remote procedure without having to deal with remote APIs.

无需使用远程API便能使得你本地的方法可以进行远程处理。

    Make a local Java method a management operation without having to deal with JMX APIs.

无需使用JMXAPI便能使得你的本地方法可以进行管理操作。

    Make a local Java method a message handler without having to deal with JMS APIs.

无需使用JMSAPI便能使得你的本地方法可以使用消息服务。

 

2.1 Dependency Injection and Inversion of Control

依赖注入和反向控制

 

A Java application——a loose term that runs the gamut from constrained, embedded applications to n-tier, server-side enterprise applications??typically consists of objects that collaborate to form the application proper. Thus the objects in an application have dependencies on each other.

一个java应用程序,可以在各个范围中运行,从约束的嵌入式应用程序到有多层结构的企业级应用,通常在应用层都是互相合作的Object。并且这些object是互相依赖的。

 

Although the Java platform provides a wealth of application development functionality, it lacks the means to organize the basic building blocks into a coherent whole, leaving that task to architects and developers. Although you can use design patterns such as Factory, Abstract Factory, Builder, Decorator, and Service Locator to compose the various classes and object instances that make up an application, these patterns are simply that: best practices given a name, with a description of what the pattern does, where to apply it, the problems it addresses, and so forth. Patterns are formalized best practices that you must implement yourself in your application.

尽管java平台提供了一套健全的应用开发平台,但是也缺乏将基础控件组合成整体的方法,并且将其留给了设计和开发人员。尽管你可以使用设计模式例如工厂、抽象工厂、builder、装饰器和service locator来将不同classobject组合起来构建你的应用。这些模式很简单,好的设计模式说明了其作用、在什么情况下使用、其能解决的问题等等。而这些模式必须你自己在应用中手动实现。

 

The Spring Framework Inversion of Control (IoC) component addresses this concern by providing a formalized means of composing disparate components into a fully working application ready for use. The Spring Framework codifies formalized design patterns as first-class objects that you can integrate into your own application(s). Numerous organizations and institutions use the Spring Framework in this manner to engineer robust, maintainable applications.

SpringIOC框架描绘了一种通过提供有效的方法使得分散的组件组合成一个完整的应用程序以方便使用的构想。Spring框架将常用的设计模式作为直接组件以便你可以方便的集成到你的应用中。许多的组织和机构将Spring框架用于管理应用。

 

Background

补充

 

"The question is, what aspect of control are [they] inverting?" Martin Fowler posed this question about Inversion of Control (IoC) on his site in 2004. Fowler suggested renaming the principle to make it more self-explanatory and came up with Dependency Injection.

问题是什么样的部分是需要进行IOC的。Martion Fowler将这个有关IOC的问题在2004年挂在了其个人页面。Fowler建议重新规划设计原则以使得其可以更加方便使用从而诞生了依赖注入。

 

2.2 Modules

模块化

 

The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test, as shown in the following diagram.

Spring框架大约由20多个模块组成。这些模块被划分为核心容器、数据访问/集成、WebAOP、设备、消息和测试,并在下面的图表中展示。

 

 

Figure 2.1. Overview of the Spring Framework

Spring框架概览

 

The following sections list the available modules for each feature along with their artifact names and the topics they cover. Artifact names correlate to artifact IDs used in Dependency Management tools.

下面的章节列出了模块及其每个模块的特性以及支持的功能。组件的名称与依赖管理工具中的ID相互关联。

 

2.2.1 Core Container

核心容器

 

The Core Container consists of the spring-core, spring-beans, spring-context, spring-context-support, and spring-expression (Spring Expression Language) modules.

核心容器包含spring-corespring-beansspring-contextspring-context-supportspring-expression组件。

 

The spring-core and spring-beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features. The BeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

spring-corespring-beans模块提供了框架最基本的功能,包括IOC和依赖注入的特性。BeanFactory是一个优秀的工厂模式的具体实现。他使得你不用去编程实现单例模式,并且允许你将配置和依赖管理从你的程序逻辑中分离。

 

The Context (spring-context) module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry. The Context module inherits its features from the Beans module and adds support for internationalization (using, for example, resource bundles), event propagation, resource loading, and the transparent creation of contexts by, for example, a Servlet container. The Context module also supports Java EE features such as EJB, JMX, and basic remoting. The ApplicationContext interface is the focal point of the Context module. spring-context-support provides support for integrating common third-party libraries into a Spring application context for caching (EhCache, Guava, JCache), mailing (JavaMail), scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports, Velocity).

spring-context模块构建在corebeans模块上,他是用框架style的访问object的方式,类似于JNDI的注册。cotext模块继承了beans的优秀特性并添加了对国际化的支持(例如,使用resource bundles)、事件传播、资源加载和方便创建上下文,例如一个servlet容器。context模块也支持Java EE的特性,例如EJBJMX和基本的远程支持。ApplicationContext接口是context模块的核心点。context-support模块支持一些第三方组件在spring的集成,比如缓存组件(EhCache, Guava, JCache)、邮件组件(JavaMail)、任务计划组件(CommonJ, Quartz)和模板引擎(FreeMarker, JasperReports, Velocity)

 

The spring-expression module provides a powerful Expression Language for querying and manipulating an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values, property assignment, method invocation, accessing the content of arrays, collections and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Springs IoC container. It also supports list projection and selection as well as common list aggregations.

spring-expression模块提供了一种强大的表达式语言用于查询和操作object graphruntime上。他是标准表达式语言的扩展,是JSP 2.1规范的详细实现。该语言支持设置和获得属性值、property assignment、方法声明、访问内容数组、容器和indexerslogical and arithmetic operatorsnamed variables、通过名称在IOC容器中需找bean。他也支持像普通的list aggregations一样list视图。

 

2.2.2 AOP and Instrumentation

AOP和设备模块

 

The spring-aop module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Using source-level metadata functionality, you can also incorporate behavioral information into your code, in a manner similar to that of .NET attributes.

spring-aop模块提供了aop面向切面的编程实现来提供给你来调用。例如,方法拦截器和实现功能的干净解耦的代码的切入点应该是分离的。使用代码层级的元数据,你也可以在你的代码中包含行为信息,有点类似于.NET的特性。

 

The separate spring-aspects module provides integration with AspectJ.

spring-aspects模块提供了与AspectJ的集成。

 

The spring-instrument module provides class instrumentation support and classloader implementations to be used in certain application servers. The spring-instrument-tomcat module contains Springs instrumentation agent for Tomcat.

spring-instrument模块提供了class工具支持和用于应用程序服务器的类加载器的实现。spring-instrument-tomcat模块包含了对tomcatspring工具。

 

2.2.3 Messaging

消息组件

 

Spring Framework 4 includes a spring-messaging module with key abstractions from the Spring Integration project such as Message, MessageChannel, MessageHandler, and others to serve as a foundation for messaging-based applications. The module also includes a set of annotations for mapping messages to methods, similar to the Spring MVC annotation based programming model.

spring框架4包括了spring-messaging模块,包括几个重要的抽象,例如MessageMessageChannelMessageHandler和其他用于基于消息的应用的功能。该模块还包含一系列的annotations,用于实现消息和方法的对应,类似于SpringMVC声明的基本程序模型。

 

2.2.4 Data Access/Integration

数据访问和集成

 

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS, and Transaction modules.

数据访问好集成包括JDBCORMOXMJMS和事务模块。

 

The spring-jdbc module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

spring-jdbc模块提供了jdbc的抽象处理,屏蔽了冗长的jdbc编码,也屏蔽了不同数据库平台的错误代码。

 

The spring-tx module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs (Plain Old Java Objects).

spring-tx模块支持编程式和声明式的事务管理,支持实现特殊接口的类和你所有的POJO

 

The spring-orm module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, and Hibernate. Using the spring-orm module you can use all of these O/R-mapping frameworks in combination with all of the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.

spring-orm模块为流行的对象关系映射模型提供了集成框架,包括JPAJDOHibernate。使用spring-orm模块你可以使用所有的orm框架并且与spring的其他特性相结合,例如前面提到的简单的声明式事务管理。

 

The spring-oxm module provides an abstraction layer that supports Object/XML mapping implementations such as JAXB, Castor, XMLBeans, JiBX and XStream.

spring-oxm模块提供了一个支持对象XML映射模型的抽象层,包括JAXBCastorXMLBeansJiBXXStream

 

The spring-jms module (Java Messaging Service) contains features for producing and consuming messages. Since Spring Framework 4.1, it provides integration with the spring-messaging module.

spring-jms模块,Java消息服务包括生产和消费消息的特性。自从spring框架4.1开始,他就集成了spring-messaging模块。

 

2.2.5 Web

 

The Web layer consists of the spring-web, spring-webmvc, spring-websocket, and spring-webmvc-portlet modules.

web层包括spring-webspring-webmvcspring-websocketspring-webmvc-portlet模块。

 

The spring-web module provides basic web-oriented integration features such as multipart file upload functionality and the initialization of the IoC container using Servlet listeners and a web-oriented application context. It also contains an HTTP client and the web-related parts of Springs remoting support.

spring-web模块提供了一些基本的面向web的集成特性,包括多文件上传、使用servlet监听的初始ioc容器和一个面向web的应用上下文。他也包含一个http客户端和web相关的spring远程支持。

 

The spring-webmvc module (also known as the Web-Servlet module) contains Springs model-view-controller (MVC) and REST Web Services implementation for web applications. Springs MVC framework provides a clean separation between domain model code and web forms and integrates with all of the other features of the Spring Framework.

spring-webmvc模块(也就是web-servlet模块)包含spring mvcweb应用的rest风格的web service实现。spring mvc框架使得程序代码与web文本相互分离,并且支持其他的spring框架的特性。

 

The spring-webmvc-portlet module (also known as the Web-Portlet module) provides the MVC implementation to be used in a Portlet environment and mirrors the functionality of the spring-webmvc module.

spring-webmvc-portlet模块(也就是web-portlet模块)使得mvc实现可以在Portlet环境中使用,并且映射了spring-webmvc模块。

 

2.2.6 Test

测试

 

The spring-test module supports the unit testing and integration testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use to test your code in isolation.

spring-test模块通过与JUnitTestNG的组合使得可以支持单元测试和集成测试。他提供了加载spring ApplicationContexts的一致性功能并且缓存了这些context。他也提供了模拟对象使得你可以在你的测试代码中实现隔离。

 

2.3 Usage scenarios

应用场景

 

The building blocks described previously make Spring a logical choice in many scenarios, from embedded applications that run on resource-constrained devices to full-fledged enterprise applications that use Springs transaction management functionality and web framework integration.

building blocks描述了之前在很多场景中选择spring,从资源贫乏的嵌入式应用到使用spring的事务管理和web框架集成的成熟的企业级应用。

 

Figure 2.2. Typical full-fledged Spring web application

典型的成熟型spring web应用

 

Springs declarative transaction management features make the web application fully transactional, just as it would be if you used EJB container-managed transactions. All your custom business logic can be implemented with simple POJOs and managed by Springs IoC container. Additional services include support for sending email and validation that is independent of the web layer, which lets you choose where to execute validation rules. Springs ORM support is integrated with JPA, Hibernate and JDO; for example, when using Hibernate, you can continue to use your existing mapping files and standard Hibernate SessionFactory configuration. Form controllers seamlessly integrate the web-layer with the domain model, removing the need for ActionForms or other classes that transform HTTP parameters to values for your domain model.

spring的声明式事务管理使得web应用可以fully transactional,就像你使用EJB容易管理事务一样。所有的用户需求都可以通过IOC容器管理的简单的pojo来实现。额外的支持包括发送email、通过你选择的检查规范来检查web层的合法性。Spring ORM使得你可以与JPAhibernateJDO集成。例如使用hibernate,你依然可以使用现有的映射文件和标准的hibernate SessionFactory配置。Form控制器无缝的与领域模型相互结合,不需要ActionForms和其他用来和领域模型传输http参数的类。

Figure 2.3. Spring middle-tier using a third-party web framework

spring使用第三方web框架工具的中间层

 

Sometimes circumstances do not allow you to completely switch to a different framework. The Spring Framework does not force you to use everything within it; it is not an all-or-nothing solution. Existing front-ends built with Struts, Tapestry, JSF or other UI frameworks can be integrated with a Spring-based middle-tier, which allows you to use Spring transaction features. You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.

在有些情形下不允许你全部切换到另一个框架。spring框架并强制要求你使用框架的每一个部分,spring框架不是一个all-or-nothing解决方案。已有的前端方案如StrutsTapestryJSF或其他UI框架可以和spring的中间层进行集成以便于你使用spring的事务特性。你只需要简单的使用ApplicationContext将你的业务包裹起来,再使用WebApplicationContext来集成你的web层。

 

Figure 2.4. Remoting usage scenario

远程使用场景

 

When you need to access existing code through web services, you can use Springs Hessian-, Burlap-, Rmi- or JaxRpcProxyFactory classes. Enabling remote access to existing applications is not difficult.

当你需要通过web service来访问你的方法,你可以使用springHessian-Burlap-Rmi-或者JaxRpcProxyFactory。使得远程方法调用很简单。

 

Figure 2.5. EJBs - Wrapping existing POJOs

EJBs——包裹已经存在POJO

 

The Spring Framework also provides an access and abstraction layer for Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in stateless session beans for use in scalable, fail-safe web applications that might need declarative security.

spring框架也为企业JavaBeans提供了访问和抽象层,使得你可以重用已有的POJO并且将他们通过session beans包裹起来,以方便用于需要声明安全的可扩展、保证安全的web应用中。

 

2.3.1 Dependency Management and Naming Conventions

依赖管理和命名规范

 

Dependency management and dependency injection are different things. To get those nice features of Spring into your application (like dependency injection) you need to assemble all the libraries needed (jar files) and get them onto your classpath at runtime, and possibly at compile time. These dependencies are not virtual components that are injected, but physical resources in a file system (typically). The process of dependency management involves locating those resources, storing them and adding them to classpaths. Dependencies can be direct (e.g. my application depends on Spring at runtime), or indirect (e.g. my application depends on commons-dbcp which depends on commons-pool). The indirect dependencies are also known as "transitive" and it is those dependencies that are hardest to identify and manage.

依赖管理和依赖注入是不同的。为了使用这些优秀的特性(比如依赖注入),你需要将所有相关的jar放入你的classpath中,并且在编译和运行时使用这些jar文件。这些依赖并不是虚拟的,而是在文件系统中实际的资源。依赖管理包括确认这些资源的位置、存储这些资源并且将他们加入classpath。依赖可以直接的(比如你的应用在运行时依赖spring),或者是间接的(比如你的应用依赖commons-dbcp,而commons-dbcp依赖于commons-pool)。间接依赖也就是我们所知道的传递,并且这样的依赖是很难定义和管理的。

 

If you are going to use Spring you need to get a copy of the jar libraries that comprise the pieces of Spring that you need. To make this easier Spring is packaged as a set of modules that separate the dependencies as much as possible, so for example if you dont want to write a web application you dont need the spring-web modules. To refer to Spring library modules in this guide we use a shorthand naming convention spring-* or spring-*.jar, where * represents the short name for the module (e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name that you use is normally the module name concatenated with the version number (e.g. spring-core-4.3.4.RELEASE.jar).

如果你使用spring或许你会将你需要的jar复制一份。为了使操作简单,spring在打包时就尽可能的将依赖分开,例如,如果你不需要web应用的话你就不需要spring-web模块。在这份文档中为了方便引用,我们使用了名字的简略,比如spring-*spring-*.jar,用*来代表模块的简写。(例如spring-corespring-webmvcspring-jms等)。而你实际用到的jar文件可能还会含有版本号(例如spring-core-4.3.4.RELEASE.jar)。

 

Each release of the Spring Framework will publish artifacts to the following places:

每一份发布的spring框架都会发布在如下的地方。

 

    Maven Central, which is the default repository that Maven queries, and does not require any special configuration to use. Many of the common libraries that Spring depends on also are available from Maven Central and a large section of the Spring community uses Maven for dependency management, so this is convenient for them. The names of the jars here are in the form spring-*-<version>.jar and the Maven groupId is org.springframework.

Maven中心仓库,是Maven查询的默认仓库,并且使用时不需要任何特殊的配置。spring依赖的很多通用的库文件在Maven中心仓库中也能找到并且对spring来说会有很多的选择,如果使用Maven作为依赖管理,这样比较方便。这些在Maven仓库中的jar的名字都有这样的形式spring-*-版本号.jar并且MavengroupIdorg.springframework.

    In a public Maven repository hosted specifically for Spring. In addition to the final GA releases, this repository also hosts development snapshots and milestones. The jar file names are in the same form as Maven Central, so this is a useful place to get development versions of Spring to use with other libraries deployed in Maven Central. This repository also contains a bundle distribution zip file that contains all Spring jars bundled together for easy download.

spring使用的公开的Maven仓库。为了方便找到GA版本,仓库也包括了spring的开发版本和milestones版本。这些jarMaven参考中的命名也相似,因此Maven仓库也是获得开发版本的spring及其他相关有用的库文件的地方。这个仓库中也包含一系列的zip文件包括spring的所有jar以方便下载。

 

So the first thing you need to decide is how to manage your dependencies: we generally recommend the use of an automated system like Maven, Gradle or Ivy, but you can also do it manually by downloading all the jars yourself.

因此首先你要决定如何管理你的依赖,我们强烈推荐使用自动化管理系统例如Maven, Gradle or Ivy,但是你也可以下载和手动管理。

 

You will find bellow the list of Spring artifacts. For a more complete description of each modules, see Section 2.2, Modules.

你可以看到下面的spring的产品。如果需要查看详细的模块描述,请看2.2章节。

Table?2.1.?Spring Framework Artifacts

GroupId

ArtifactId

Description

org.springframework

spring-aop

Proxy-based AOP support

org.springframework

spring-aspects

AspectJ based aspects

org.springframework

spring-beans

Beans support, including Groovy

org.springframework

spring-context

Application context runtime, including scheduling and remoting abstractions

org.springframework

spring-context-support

Support classes for integrating common third-party libraries into a Spring application context

org.springframework

spring-core

Core utilities, used by many other Spring modules

org.springframework

spring-expression

Spring Expression Language (SpEL)

org.springframework

spring-instrument

Instrumentation agent for JVM bootstrapping

org.springframework

spring-instrument-tomcat

Instrumentation agent for Tomcat

org.springframework

spring-jdbc

JDBC support package, including DataSource setup and JDBC access support

org.springframework

spring-jms

JMS support package, including helper classes to send and receive JMS messages

org.springframework

spring-messaging

Support for messaging architectures and protocols

org.springframework

spring-orm

Object/Relational Mapping, including JPA and Hibernate support

org.springframework

spring-oxm

Object/XML Mapping

org.springframework

spring-test

Support for unit testing and integration testing Spring components

org.springframework

spring-tx

Transaction infrastructure, including DAO support and JCA integration

org.springframework

spring-web

Web support packages, including client and web remoting

org.springframework

spring-webmvc

REST Web Services and model-view-controller implementation for web applications

org.springframework

spring-webmvc-portlet

MVC implementation to be used in a Portlet environment

org.springframework

spring-websocket

WebSocket and SockJS implementations, including STOMP support

Spring Dependencies and Depending on Spring

spring的依赖和依赖spring

 

Although Spring provides integration and support for a huge range of enterprise and other external tools, it intentionally keeps its mandatory dependencies to an absolute minimum: you shouldnt have to locate and download (even automatically) a large number of jar libraries in order to use Spring for simple use cases. For basic dependency injection there is only one mandatory external dependency, and that is for logging (see below for a more detailed description of logging options).

尽管spring提供了对企业提供的强有力的功能,当时spring也尽量保证依赖的最小性,以方便当你使用一个小功能时不需要下载太多的jar文件。例如依赖注入功能只有一个外部依赖,而那个依赖使用用来记录日志的。(后面有关于日志记录的详细介绍)

 

Next we outline the basic steps needed to configure an application that depends on Spring, first with Maven and then with Gradle and finally using Ivy. In all cases, if anything is unclear, refer to the documentation of your dependency management system, or look at some sample code - Spring itself uses Gradle to manage dependencies when it is building, and our samples mostly use Gradle or Maven.

下面我们简要介绍一下依赖spring搭建应用的步骤,首先将使用Maven,然后是Gradle,最后是Ivy。在所有的例子中,如果对依赖管理系统的文档有什么不理解的,或者对一些样例代码有疑问,spring自身是使用Gradle来够简单,并且我们简单使用了GradleMaven

 

Maven Dependency Management

Maven依赖管理

 

If you are using Maven for dependency management you dont even need to supply the logging dependency explicitly. For example, to create an application context and use dependency injection to configure an application, your Maven dependencies will look like this:

如果你使用Maven作为依赖管理,那么你不用显式的声明对logging的依赖。例如,如果使用依赖注入来构建一个应用,你的Maven文件看起来应该是这样的。

<dependencies>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-context</artifactId>

        <version>4.3.4.RELEASE</version>

        <scope>runtime</scope>

    </dependency>

</dependencies>

Thats it. Note the scope can be declared as runtime if you dont need to compile against Spring APIs, which is typically the case for basic dependency injection use cases.

就这些。声明范围是运行时,如果你不需要再编译时使用springapi的话。这是典型的使用依赖注入的例子。

 

The example above works with the Maven Central repository. To use the Spring Maven repository (e.g. for milestones or developer snapshots), you need to specify the repository location in your Maven configuration. For full releases:

上面的例子需要Maven的中心仓库才可以工作。如果使用springMaven仓库(例如开发版本或milestones),你需要设定仓库的位置在Maven的设置宏。比如所有的release版本如下:

<repositories>

    <repository>

        <id>io.spring.repo.maven.release</id>

        <url>http://repo.spring.io/release/</url>

        <snapshots><enabled>false</enabled></snapshots>

    </repository>

</repositories>

For milestones:

如果是milestones的话如下:

<repositories>

    <repository>

        <id>io.spring.repo.maven.milestone</id>

        <url>http://repo.spring.io/milestone/</url>

        <snapshots><enabled>false</enabled></snapshots>

    </repository>

</repositories>

 

And for snapshots:

如果是开发的镜像的话如下:

<repositories>

    <repository>

        <id>io.spring.repo.maven.snapshot</id>

        <url>http://repo.spring.io/snapshot/</url>

        <snapshots><enabled>true</enabled></snapshots>

    </repository>

</repositories>

Maven "Bill Of Materials" Dependency

Maven的清单依赖

 

It is possible to accidentally mix different versions of Spring JARs when using Maven. For example, you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

在使用Maven时很有可能混合了不同版本的springjar文件。例如,你或许找到了第三方的库或者其他spring的工程,或者传递依赖了一个过时的版本。如果你忘记显式的进行声明,很多你意想不到的问题会出现。

 

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency. You can import the spring-framework-bom in your dependencyManagement section to ensure that all spring dependencies (both direct and transitive) are at the same version.

为了解决这样的问题,Maven支持BOM的概念依赖。你可以引入spring-framework-bom在你的依赖管理中,以保证所有的spring依赖都在同一个版本上。

<dependencyManagement>

    <dependencies>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-framework-bom</artifactId>

            <version>4.3.4.RELEASE</version>

            <type>pom</type>

            <scope>import</scope>

        </dependency>

    </dependencies>

</dependencyManagement>

 

An added benefit of using the BOM is that you no longer need to specify the <version> attribute when depending on Spring Framework artifacts:

使用BOM的好处在于你依赖spring框架时再也不需要声明版本号了。

<dependencies>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-context</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-web</artifactId>

    </dependency>

<dependencies>

Gradle Dependency Management

Gradle的依赖管理

 

To use the Spring repository with the Gradle build system, include the appropriate URL in the repositories section:

使用Gradle管理spring来构建系统,包括适合的URL地址。

 

repositories {

    mavenCentral()

    // and optionally...

    maven { url "http://repo.spring.io/release" }

}

You can change the repositories URL from /release to /milestone or /snapshot as appropriate. Once a repository has been configured, you can declare dependencies in the usual Gradle way:

你可以将URL/release改为/milestone/snapshot,选择一个合适的。一旦仓库配置好了,你就可以使用Gradle的方式配置依赖了。

 

dependencies {

    compile("org.springframework:spring-context:4.3.4.RELEASE")

    testCompile("org.springframework:spring-test:4.3.4.RELEASE")

}

 

Ivy Dependency Management

Ivy的依赖管理

 

If you prefer to use Ivy to manage dependencies then there are similar configuration options.

如果你倾向于使用Ivy来管理依赖,那么下面提供一下简单的配置选项。

 

To configure Ivy to point to the Spring repository add the following resolver to your ivysettings.xml:

配置Ivy指向spring的仓库,你需要修改ivysettings.xml文件。

 

<resolvers>

    <ibiblio name="io.spring.repo.maven.release"

            m2compatible="true"

            root="http://repo.spring.io/release/"/>

</resolvers>

 

You can change the root URL from /release/ to /milestone/ or /snapshot/ as appropriate.

你可以将root URL/release改为/milestone/snapshot,选择一个合适的。

 

Once configured, you can add dependencies in the usual way. For example (in ivy.xml):

一旦配置好了,你就可以添加依赖了,例如(在ivy.xml文件中)

 

<dependency org="org.springframework"

name="spring-core" rev="4.3.4.RELEASE" conf="compile->runtime"/>

Distribution Zip Files

发布的zip文件

 

Although using a build system that supports dependency management is the recommended way to obtain the Spring Framework, it is still possible to download a distribution zip file.

尽管通过依赖管理获得spring是推荐的方式,但是我们依然也支持直接下载spring发布的zip文件。

 

Distribution zips are published to the Spring Maven Repository (this is just for our convenience, you dont need Maven or any other build system in order to download them).

发布的zip文件会加入springMaven仓库(但是这只是为了我们方便,你不需要使用Maven或其他构建系统来下载他们)

 

To download a distribution zip open a web browser to http://repo.spring.io/release/org/springframework/spring and select the appropriate subfolder for the version that you want. Distribution files end -dist.zip, for example spring-framework-{spring-version}-RELEASE-dist.zip. Distributions are also published for milestones and snapshots.

为了下载发布的zip包,你需要打开http://repo.spring.io/release/org/springframework/spring,然后通过你需要的版本选择合适的子文件夹。发布的zip文件通常以-dist.zip结尾,例如spring-framework-{spring-version}-RELEASE-dist.zip。发布的zip文件也包括milestones版本和snapshots版本。

 

2.3.2 Logging

日志记录

 

Logging is a very important dependency for Spring because a) it is the only mandatory external dependency, b) everyone likes to see some output from the tools they are using, and c) Spring integrates with lots of other tools all of which have also made a choice of logging dependency. One of the goals of an application developer is often to have unified logging configured in a central place for the whole application, including all external components. This is more difficult than it might have been since there are so many choices of logging framework.

日志记录对于spring来说是十分重要的依赖。因为

a)他是唯一被强制需要的外部依赖

b)每个人都希望他在使用某个工具时可以看到一些输出

cspring集成的很多工具都选择了日志依赖

一个应用开发者的其中一个目标就是不需要为了整个应用指定日志配置,包括外部的组件。选择如此多的spring框架组件后,这是很困难的。

 

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We compile against JCL and we also make JCL Log objects visible for classes that extend the Spring Framework. Its important to users that all versions of Spring use the same logging library: migration is easy because backwards compatibility is preserved even with applications that extend Spring. The way we do this is to make one of the modules in Spring depend explicitly on commons-logging (the canonical implementation of JCL), and then make all the other modules depend on that at compile time. If you are using Maven for example, and wondering where you picked up the dependency on commons-logging, then it is from Spring and specifically from the central module called spring-core.

强制的日志依赖使用的是Jakarta Commons Logging APIJCL)。我们使用JCL和我们一起编译,也是的JCL可以被所有的spring框架可见。对于用户来说使用统一的日志管理是重要的,这样对于后续的迁移也是十分简单的。我们这样做使得spring的其中一个模块明确依赖于commons-logging(典型的JCL实现),然后使得其他模块在编译时依赖于此模块。例如你使用Maven,并且想知道是是哪个模块依赖了commons-logging,那可以告诉你是来自spring的,并且明确是我们的核心模块,叫spring-core

 

The nice thing about commons-logging is that you dont need anything else to make your application work. It has a runtime discovery algorithm that looks for other logging frameworks in well known places on the classpath and uses one that it thinks is appropriate (or you can tell it which one if you need to). If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short). You should find that your Spring application works and logs happily to the console out of the box in most situations, and thats important.

对于commons-logging来说,优点是你不需要任何其他配置来保证你应用的运作。他有一个运行时发现算法可以在你的classpath中需找日志框架并且使用其中一个合适的(或者如果你需要的话也可以手动配置)。如果没有比较好的日志框架来自JDKjava.util.logging,使用JUL来简写),你应该很开心的可以看到在大多数环境下的日志输出,并且这很重要。

 

Not Using Commons Logging

不使用通用的日志记录

 

Unfortunately, the runtime discovery algorithm in commons-logging, while convenient for the end-user, is problematic. If we could turn back the clock and start Spring now as a new project it would use a different logging dependency. The first choice would probably be the Simple Logging Facade for Java ( SLF4J), which is also used by a lot of other tools that people use with Spring inside their applications.

不幸的是,commons-logging的运行时日志发现算法对于终端用户来说是存在问题的。如果我们可以回到过去重新建立一个spring框架的话,我们会选择一个其他的日志依赖。我们第一个选择就是Simple Logging Facade for Java ( SLF4J),并且这个工具也被广泛使用在spring的应用中。

 

There are basically two ways to switch off commons-logging:

有两种方式可以关闭commons-logging

 

    Exclude the dependency from the spring-core module (as it is the only module that explicitly depends on commons-logging)

拒绝使用spring-core模块依赖(这是唯一一个依赖于commons-logging的模块)

    Depend on a special commons-logging dependency that replaces the library with an empty jar (more details can be found in the SLF4J FAQ)

使用一个其他的commons-logging依赖替换原有库,使用一个空的jar(具体细节请参考SLF4JFAQ

 

To exclude commons-logging, add the following to your dependencyManagement section:

排除commons-logging,可以在依赖管理中添加如下的内容。

<dependencies>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-core</artifactId>

        <version>4.3.4.RELEASE</version>

        <exclusions>

            <exclusion>

                <groupId>commons-logging</groupId>

                <artifactId>commons-logging</artifactId>

            </exclusion>

        </exclusions>

    </dependency>

</dependencies>

Now this application is probably broken because there is no implementation of the JCL API on the classpath, so to fix it a new one has to be provided. In the next section we show you how to provide an alternative implementation of JCL using SLF4J as an example.

现在这个应用因为没有JCL API的实现而不完整,因此为了修复这个问题需要提供一个新的实现。在下一个节中我们将介绍如何使用另外一个JCL的实现,并以SLF4J来举例。

 

Using SLF4J

使用SLF4J

 

SLF4J is a cleaner dependency and more efficient at runtime than commons-logging because it uses compile-time bindings instead of runtime discovery of the other logging frameworks it integrates. This also means that you have to be more explicit about what you want to happen at runtime, and declare it or configure it accordingly. SLF4J provides bindings to many common logging frameworks, so you can usually choose one that you already use, and bind to that for configuration and management.

SLF4J是一个干净的依赖,并且在运行时比commons-logging更加有效,因为他使用了编译时绑定而不是运行时发现其他日志框架后在集成。这也意味着你必须更加明确在运行时你希望发生什么,并且以此来正确的声明和配置。SLF4J提供了对许多通用日志管理框架的绑定,因此你可以选择一个你已经在使用的框架,并且在配置和管理中绑定他们。

 

SLF4J provides bindings to many common logging frameworks, including JCL, and it also does the reverse: bridges between other logging frameworks and itself. So to use SLF4J with Spring you need to replace the commons-logging dependency with the SLF4J-JCL bridge. Once you have done that then logging calls from within Spring will be translated into logging calls to the SLF4J API, so if other libraries in your application use that API, then you have a single place to configure and manage logging.

SLF4J提供了对许多通用日志管理框架的绑定,包括JCL并且他也允许支持反向操作,是他和其他日志框架的桥梁。因此为了使用SLF4Jspring配合,你需要替换commons-logging依赖通过SLF4J-JCL桥。这样spring框架中的日志记录将会调用SLF4JAPI,因此如果其他库在你的应用中使用此api,你只需要简单的进行配置。

 

A common choice might be to bridge Spring to SLF4J, and then provide explicit binding from SLF4J to Log4J. You need to supply 4 dependencies (and exclude the existing commons-logging): the bridge, the SLF4J API, the binding to Log4J, and the Log4J implementation itself. In Maven you would do that like this

一个简单的选择是建立springSLF4J的桥,然后明确声明将SLF4JLog4J绑定。你需要4个依赖(包括排除的已经存在的commons-logging),桥,SLF4JAPI,和绑定Log4JLog4J的实现本身。在Maven中你可以这样配置

<dependencies>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-core</artifactId>

        <version>4.3.4.RELEASE</version>

        <exclusions>

            <exclusion>

                <groupId>commons-logging</groupId>

                <artifactId>commons-logging</artifactId>

            </exclusion>

        </exclusions>

    </dependency>

    <dependency>

        <groupId>org.slf4j</groupId>

        <artifactId>jcl-over-slf4j</artifactId>

        <version>1.5.8</version>

    </dependency>

    <dependency>

        <groupId>org.slf4j</groupId>

        <artifactId>slf4j-api</artifactId>

        <version>1.5.8</version>

    </dependency>

    <dependency>

        <groupId>org.slf4j</groupId>

        <artifactId>slf4j-log4j12</artifactId>

        <version>1.5.8</version>

    </dependency>

    <dependency>

        <groupId>log4j</groupId>

        <artifactId>log4j</artifactId>

        <version>1.2.14</version>

    </dependency>

</dependencies>

 

That might seem like a lot of dependencies just to get some logging. Well it is, but it is optional, and it should behave better than the vanilla commons-logging with respect to classloader issues, notably if you are in a strict container like an OSGi platform. Allegedly there is also a performance benefit because the bindings are at compile-time not runtime.

为了记录日志,似乎需要很多依赖。事实是这样,但这也是可选的。但是总比commons-logging要好,因为他的类加载器问题,尤其是你在一些比较严格的OSGi平台上使用。并且在编译时绑定比在运行时绑定更加有效率。

 

A more common choice amongst SLF4J users, which uses fewer steps and generates fewer dependencies, is to bind directly to Logback. This removes the extra binding step because Logback implements SLF4J directly, so you only need to depend on two libraries not four ( jcl-over-slf4j and logback). If you do that you might also need to exclude the slf4j-api dependency from other external dependencies (not Spring), because you only want one version of that API on the classpath.

一个对于SLF4J用户更方便的选择,使用少量步骤和少量的依赖,就是直接Logback。这去除了一些额外的绑定,因为Logback直接实现了SLF4J,因此你只需要依赖两个库而不是四个(jclslf4j桥、logback)。如果你这样做,你还需要从其他库中将slf4japi刨除,因为同一个版本的api只需要一个在classpath中。

 

Using Log4J

使用Log4J

 

Many people use Log4j as a logging framework for configuration and management purposes. Its efficient and well-established, and in fact its what we use at runtime when we build and test Spring. Spring also provides some utilities for configuring and initializing Log4j, so it has an optional compile-time dependency on Log4j in some modules.

许多用户使用Log4J作为日志模块来管理和配置。这是一个有效并且容易使用的,也是我们在构建spring时运行时使用的。spring也提供了一些组件来与log4j来配置和集成,因此对于一些模块可以使用log4j作为编译时的依赖选择。

 

To make Log4j work with the default JCL dependency ( commons-logging) all you need to do is put Log4j on the classpath, and provide it with a configuration file ( log4j.properties or log4j.xml in the root of the classpath). So for Maven users this is your dependency declaration:

为了让log4j作为默认的JCL依赖,你需要做的就是讲log4j放入classpath中,然后提供一个配置文件(log4j.properties log4j.xml在你的classpath根路径)。对于Maven用户来说你的依赖是这样的。

<dependencies>

    <dependency>

        <groupId>org.springframework</groupId>

        <artifactId>spring-core</artifactId>

        <version>4.3.4.RELEASE</version>

    </dependency>

    <dependency>

        <groupId>log4j</groupId>

        <artifactId>log4j</artifactId>

        <version>1.2.14</version>

    </dependency>

</dependencies>

And heres a sample log4j.properties for logging to the console:

下面例子是一个简单的log4j.properties示例,用于向控制台打印日志。

 

log4j.rootCategory=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n

log4j.category.org.springframework.beans.factory=DEBUG

 

Runtime Containers with Native JCL

使用本地JCL的运行时容器

 

Many people run their Spring applications in a container that itself provides an implementation of JCL. IBM Websphere Application Server (WAS) is the archetype. This often causes problems, and unfortunately there is no silver bullet solution; simply excluding commons-logging from your application is not enough in most situations.

许多人的spring应用在他们已经实现JCL的容器中运行。IBM Websphere Application Server (WAS)就是其中一个。这样会造成很多问题,并且没有什么特别好的解决方案,将commons-logging抛出在很多情况下无法解决问题。

 

To be clear about this: the problems reported are usually not with JCL per se, or even with commons-logging: rather they are to do with binding commons-logging to another framework (often Log4J). This can fail because commons-logging changed the way they do the runtime discovery in between the older versions (1.0) found in some containers and the modern versions that most people use now (1.1). Spring does not use any unusual parts of the JCL API, so nothing breaks there, but as soon as Spring or your application tries to do any logging you can find that the bindings to Log4J are not working.

为了更加清楚,问题一般不会以JCL的形式出现,或者commons-logging,或许会以绑定的其他日志框架(比如log4j)来出现。之所以会失败是因为commons-logging在大多数人使用的1.1版本中改进了运行时日志发现机制,比1.0版本。spring并没有使用任何非正常的JCL API的部分,因此这里不会有问题,但是很快spirng和你的程序试图绑定的任何日志框架都会失效。

 

In such cases with WAS the easiest thing to do is to invert the class loader hierarchy (IBM calls it "parent last") so that the application controls the JCL dependency, not the container. That option isnt always open, but there are plenty of other suggestions in the public domain for alternative approaches, and your mileage may vary depending on the exact version and feature set of the container.

在这种使用WAS的情况下,简单的做法是反转已经集成的类加载器(IBM叫他 "parent last")因此你的应用可以完全控制JCL依赖而不是由容器来控制。这个选项默认是关闭的,但是你可以找到很多建议在public domain中,并且这和你实际使用的版本和容器的特性是密切相关的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值